Skip to content
Official PYQ · 2006

GATE CS 2006 Q54 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Given two arrays of numbers a1,...,ana_{1},...,a_{n} and b1,...,bnb_{1},...,b_{n} where each number is 00 or 11, the fastest algorithm to find the largest span (i,j)(i, j) such that ai+ai+1+⋯+aj=bi+bi+1+⋯+bja_{i}+a_{i+1}+\dots+a_{j}=b_{i}+b_{i+1}+\dots+b_{j} or report that there is not such span,

Choose one option
View worked solution

Answer: C

The problem asks us to find the largest span (i,j)(i, j) such that:

ai+ai+1+⋯+aj=bi+bi+1+⋯+bja_{i} + a_{i+1} + \dots + a_{j} = b_{i} + b_{i+1} + \dots + b_{j}

This can be rewritten as:

∑k=ij(ak−bk)=0\sum_{k=i}^{j} (a_k - b_k) = 0

Let ck=ak−bkc_k = a_k - b_k. Since ak,bk∈{0,1}a_k, b_k \in \{0, 1\}, the value of ckc_k can only be −1-1, 00, or 11.

Let SpS_p be the prefix sum of array cc up to index pp:

Sp=∑k=1pckwithS0=0S_p = \sum_{k=1}^{p} c_k \quad \text{with} \quad S_0 = 0

The condition ∑k=ijck=0\sum_{k=i}^{j} c_k = 0 is equivalent to:

Sj−Si−1=0  ⟹  Sj=Si−1S_j - S_{i-1} = 0 \implies S_j = S_{i-1}

To find the largest span (i,j)(i, j) where Sj=Si−1S_j = S_{i-1}, we want to maximize j−i+1j - i + 1. This means for each unique prefix sum value, we want to find its first occurrence and its last occurrence.

Algorithm Steps:

  1. Compute the prefix sums S0,S1,…,SnS_0, S_1, \dots, S_n. Since ck∈{−1,0,1}c_k \in \{-1, 0, 1\}, the prefix sum SpS_p must lie in the range [−n,n][-n, n].
  2. Initialize an auxiliary array first_occurrence of size 2n+12n + 1 with −1-1 to store the first index at which each prefix sum value is seen. (We can map the range [−n,n][-n, n] to [0,2n][0, 2n] by adding an offset of nn).
  3. Traverse the prefix sums from p=0p = 0 to nn:
    • If first_occurrence[S_p] is −1-1, set it to pp.
    • Otherwise, a span with sum 00 exists from index first_occurrence[Sp]+1\text{first\_occurrence}[S_p] + 1 to pp. The length of this span is p−first_occurrence[Sp]p - \text{first\_occurrence}[S_p]. Update the maximum span length if this is larger than the current maximum.

Complexity Analysis:

  • Time Complexity: We perform a single pass over the array of size nn. Each lookup and update in the auxiliary array takes O(1)O(1) time. Thus, the total time complexity is Θ(n)\Theta(n).
  • Space Complexity: The auxiliary array of size 2n+12n + 1 requires Θ(n)\Theta(n) extra space.

Therefore, the fastest algorithm takes Θ(n)\Theta(n) time and space.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions