Arrays January 20 ,2026

Maximum Length Subarray with Given GCD

Problem Statement

You are given an integer array arr and an integer k.

Your task is to find the maximum length of a contiguous subarray whose GCD (Greatest Common Divisor) is exactly equal to k.

Example 1

Input
arr = [2, 4, 6, 8], k = 2

Output
4

Explanation
GCD of entire array = 2

Example 2

Input
arr = [3, 6, 9, 12], k = 3

Output
4

Example 3

Input
arr = [2, 4, 8, 16], k = 4

Output
3
Subarray [4, 8, 16]

Why This Problem Is Important

  • Tests understanding of GCD properties
  • Introduces subarray compression using GCD
  • Common in Google, Codeforces, LeetCode
  • Foundation for range-GCD optimization problems

Approaches Overview

ApproachTechniqueTimeSpace
Brute ForceCheck all subarraysO(n² log M)O(1)
OptimizedGCD compressionO(n log M)O(log M)

(M = maximum element value)

Approach 1 -Brute Force Approach

Idea

  • Consider every subarray
  • Maintain running GCD
  • If GCD becomes less than k, break
  • If GCD equals k, update answer

Time and Space Complexity

  • Time: O(n² log M)
  • Space: O(1)

Python Implementation 

import math

def maxLenSubarrayGCD(arr, k):
    n = len(arr)
    ans = 0

    for i in range(n):
        g = 0
        for j in range(i, n):
            g = math.gcd(g, arr[j])
            if g < k:
                break
            if g == k:
                ans = max(ans, j - i + 1)
    return ans

C++ Implementation 

#include 
using namespace std;

int maxLenSubarrayGCD(vector& arr, int k){
    int n = arr.size();
    int ans = 0;

    for(int i=0;i

Java Implementation 

class Main {
    static int gcd(int a, int b){
        if(b == 0) return a;
        return gcd(b, a % b);
    }

    static int maxLenSubarrayGCD(int[] arr, int k){
        int n = arr.length;
        int ans = 0;

        for(int i=0;i

JavaScript Implementation 

function gcd(a, b){
    while(b !== 0){
        let t = b;
        b = a % b;
        a = t;
    }
    return a;
}

function maxLenSubarrayGCD(arr, k){
    let n = arr.length;
    let ans = 0;

    for(let i=0;i

C# Implementation 

static int GCD(int a, int b){
    while(b != 0){
        int t = b;
        b = a % b;
        a = t;
    }
    return a;
}

static int MaxLenSubarrayGCD(int[] arr, int k){
    int n = arr.Length;
    int ans = 0;

    for(int i=0;i

Output

2

Approach 2- Optimized Approach (GCD Compression)

Idea

  • For each index, maintain a map of {gcd_value : max_length}
  • Extend previous subarrays by current element
  • GCD values reduce fast (log M)
  • Track longest subarray where GCD equals k

Time and Space Complexity

  • Time: O(n log M)
  • Space: O(log M)

Python Implementation 

import math

def maxLenSubarrayGCD(arr, k):
    ans = 0
    prev = {}

    for num in arr:
        curr = {}
        curr[num] = 1

        for g, length in prev.items():
            new_g = math.gcd(g, num)
            curr[new_g] = max(curr.get(new_g, 0), length + 1)

        if k in curr:
            ans = max(ans, curr[k])

        prev = curr

    return ans

C++ Implementation 

#include 
using namespace std;

int maxLenSubarrayGCD(vector& arr, int k){
    unordered_map prev, curr;
    int ans = 0;

    for(int num : arr){
        curr.clear();
        curr[num] = 1;

        for(auto &p : prev){
            int g = gcd(p.first, num);
            curr[g] = max(curr[g], p.second + 1);
        }

        if(curr.count(k))
            ans = max(ans, curr[k]);

        prev = curr;
    }
    return ans;
}

Java Implementation 

import java.util.*;

class Main {
    static int gcd(int a, int b){
        return b == 0 ? a : gcd(b, a % b);
    }

    static int maxLenSubarrayGCD(int[] arr, int k){
        Map prev = new HashMap<>();
        int ans = 0;

        for(int num : arr){
            Map curr = new HashMap<>();
            curr.put(num, 1);

            for(Map.Entry e : prev.entrySet()){
                int g = gcd(e.getKey(), num);
                curr.put(g, Math.max(curr.getOrDefault(g, 0), e.getValue() + 1));
            }

            if(curr.containsKey(k))
                ans = Math.max(ans, curr.get(k));

            prev = curr;
        }
        return ans;
    }
}

JavaScript Implementation 

function gcd(a, b){
    while(b !== 0){
        let t = b;
        b = a % b;
        a = t;
    }
    return a;
}

function maxLenSubarrayGCD(arr, k){
    let prev = new Map();
    let ans = 0;

    for(let num of arr){
        let curr = new Map();
        curr.set(num, 1);

        for(let [g, len] of prev){
            let ng = gcd(g, num);
            curr.set(ng, Math.max(curr.get(ng) || 0, len + 1));
        }

        if(curr.has(k))
            ans = Math.max(ans, curr.get(k));

        prev = curr;
    }
    return ans;
}

C# Implementation 

static int GCD(int a, int b){
    while(b != 0){
        int t = b;
        b = a % b;
        a = t;
    }
    return a;
}

static int MaxLenSubarrayGCD(int[] arr, int k){
    Dictionary prev = new Dictionary();
    int ans = 0;

    foreach(int num in arr){
        Dictionary curr = new Dictionary();
        curr[num] = 1;

        foreach(var p in prev){
            int g = GCD(p.Key, num);
            curr[g] = Math.Max(curr.ContainsKey(g) ? curr[g] : 0, p.Value + 1);
        }

        if(curr.ContainsKey(k))
            ans = Math.Max(ans, curr[k]);

        prev = curr;
    }
    return ans;
}

Output

2

Final Summary

ApproachUse Case
Brute ForceSmall constraints
Optimized GCDInterview standard

Next Problem in the Series

Count Subarrays with Product Less Than K

 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Array Data...
Arrays December 12 ,2025

Array Data Structure

Array Memo...
Arrays December 12 ,2025

Array Memory Represe...

Array Oper...
Arrays December 12 ,2025

Array Operations and...

Advantages...
Arrays December 12 ,2025

Advantages and Disad...

Arrays in...
Arrays December 12 ,2025

Arrays in C

Vector in...
Arrays December 12 ,2025

Vector in C++ STL

Arrays vs...
Arrays December 12 ,2025

Arrays vs ArrayList...

JavaScript...
Arrays December 12 ,2025

JavaScript Arrays

Binary Sea...
Arrays December 12 ,2025

Binary Search on Arr...

Two Pointe...
Arrays January 01 ,2026

Two Pointers Techniq...

Prefix Sum...
Arrays January 01 ,2026

Prefix Sum Technique

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Techn...

Basics of...
Arrays January 01 ,2026

Basics of Hashing fo...

Traverse a...
Arrays January 01 ,2026

Traverse an Array

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Print Arra...
Arrays January 01 ,2026

Print Array Elements...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Maximum Ci...
Arrays January 01 ,2026

Maximum Circular Sub...

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Smallest S...
Arrays January 01 ,2026

Smallest Subarray wi...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Submatri...

Count Suba...
Arrays January 01 ,2026

Count Subarrays with...

Longest Ar...
Arrays January 01 ,2026

Longest Arithmetic S...

Find the M...
Arrays January 01 ,2026

Find the Median in a...

Split Arra...
Arrays January 01 ,2026

Split Array Largest...

Minimum Co...
Arrays January 01 ,2026

Minimum Cost to Make...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product of T...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Subarray w...
Arrays January 01 ,2026

Subarray with Maximu...

Find All S...
Arrays January 01 ,2026

Find All Subarrays w...

Partition...
Arrays January 01 ,2026

Partition Array into...

Maximum Ab...
Arrays January 01 ,2026

Maximum Absolute Dif...

Smallest M...
Arrays January 01 ,2026

Smallest Missing Num...

Find Repea...
Arrays January 01 ,2026

Find Repeating and M...

Count Suba...
Arrays January 01 ,2026

Count Subarrays with...

Kth Larges...
Arrays January 01 ,2026

Kth Largest Element...

Minimum Op...
Arrays January 01 ,2026

Minimum Operations t...

Find Lexic...
Arrays January 01 ,2026

Find Lexicographical...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com