BackeasyStringsHCLPhonePe

Iterative Target Index Solution

Problem Statement

Given an array or sequence of length N representing numerical values or system metrics, compute the iterative target index according to the target algorithm rules.

Example 1
Input
[4, 7, 10, 13]
Output
34

Explanation: Step-by-step: 1. Initialize the target index to 0. 2. Iterate through the array from left to right. 3. For each element, add it to the target index. 4. After iterating through the entire array, the target index will be the sum of all elements.

Example 2
Input
[4, 8]
Output
12

Explanation: Step-by-step: 1. Initialize the target index to 0. 2. Iterate through the array from left to right. 3. For each element, add it to the target index. 4. After iterating through the entire array, the target index will be the sum of all elements.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Iterative Target Index — Problem Statement & Solution Guide

StringsEasyCharacter Frequency Map
TimeO(log N)
|
SpaceO(1)

Problem Description

Given an array or sequence of length N representing numerical values or system metrics, compute the iterative target index according to the target algorithm rules.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Iterative Target Index"

easy

WHY DOES IT MATTER?

Efficient search is critical in systems that handle large volumes of data, such as search engines, in‑memory caches, and real‑time analytics. A logarithmic algorithm reduces latency from seconds to milliseconds, directly impacting user experience and resource utilization.

OPTIMIZATION CHALLENGE

The core insight is to eliminate half of the remaining candidates in each iteration by leveraging the sorted property, thereby reducing the number of comparisons from linear to logarithmic. Implementing this requires careful handling of indices to avoid overflow and off‑by‑one errors.

REAL-WORLD CONNECTION

In database indexing, B‑trees use binary search at each node to locate keys, enabling quick retrieval of records even in terabyte‑scale tables. Similarly, distributed hash tables use binary search‑like techniques to locate shards in a consistent hashing ring.

When coding binary search, always compute the middle index as low + (high - low) / 2 to prevent integer overflow, and use a while (low <= high) loop to ensure all elements are considered. Also, test edge cases where the target is at the extremes or not present at all.

COMPLEXITY AT A GLANCE

⏱ Time:O(log N)
💾 Space:O(1)

Core Theory — Why This Approach?

Binary search is a classic divide‑and‑conquer algorithm that efficiently locates a target value in a sorted array by repeatedly halving the search interval. The key insight is that, because the array is sorted, any element to the left of a middle element that is greater than the target cannot contain the target, and vice versa. This eliminates half of the remaining candidates in each step, yielding a logarithmic time complexity of O(log N). Naïve linear search, which checks each element sequentially, has a linear time complexity of O(N) and becomes prohibitively slow for large datasets such as millions of records in a database or log entries in a monitoring system. The optimal iterative paradigm uses two indices—low and high—to represent the current search bounds, calculates the middle index, compares the middle element to the target, and then narrows the bounds accordingly, all while maintaining constant auxiliary space.

Interview Questions on This Problem

Q1Explain how iterative binary search works and why it is preferred over recursive binary search in interview settings.

Iterative binary search maintains two pointers, low and high, to the current search bounds. In each loop, it calculates mid = low + (high - low) / 2 to avoid overflow, compares the middle element to the target, and then moves low or high to narrow the interval. It is preferred because it uses O(1) space and avoids the overhead of recursive calls, making it easier to reason about and less prone to stack overflow.

Q2How would you modify binary search to find the first occurrence of a target in a sorted array that may contain duplicates?

After finding an occurrence of the target, continue searching the left half by setting high = mid - 1 while recording the current index as a potential answer. This ensures that the algorithm keeps looking for earlier occurrences until the leftmost one is found, resulting in O(log N) time.

Q3Describe how binary search can be adapted to work on a rotated sorted array and what the time complexity remains.

When the array is rotated, compare the target with the element at low to determine which half is properly sorted. If the target lies within the sorted half, adjust high or low accordingly; otherwise, search the other half. This preserves the O(log N) time complexity because each iteration still halves the search space.

Examples

Example 1

Input

[4, 7, 10, 13]

Output

34

Explanation: Step-by-step: 1. Initialize the target index to 0. 2. Iterate through the array from left to right. 3. For each element, add it to the target index. 4. After iterating through the entire array, the target index will be the sum of all elements.

Example 2

Input

[4, 8]

Output

12

Explanation: Step-by-step: 1. Initialize the target index to 0. 2. Iterate through the array from left to right. 3. For each element, add it to the target index. 4. After iterating through the entire array, the target index will be the sum of all elements.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)

Optimal Approach & Strategy

Iteratively maintain low and high indices, compute mid = low + (high - low) / 2, compare the middle element to the target, and adjust the bounds accordingly until the target is found or the bounds cross, achieving O(log N) time and O(1) space.

Brute Force Approach

Scan each element from the start until the target is found or the array ends, which takes O(N) time and O(1) space.

Verified Code Solutions

JavaScript Solution
Time: O(log N)
function solution(nums) {
   let targetIndex = 0;
   for (let num of nums) {
       targetIndex += num;
   }
   return targetIndex;
}

Asked in Top Tech Interviews

HCLPhonePe

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.