Array Interview Questions

Learn Array Interview Questions with practical examples, explanations, best practices, and real-world coding techniques.

Array Interview Questions

Arrays are one of the most frequently tested data structures in technical interviews. They are simple to understand but can be used to test a wide range of problem-solving skills, including searching, sorting, indexing, hashing, two-pointer techniques, sliding windows, prefix sums, and in-place manipulation.

Interview questions involving arrays often look simple at first. The main challenge is usually identifying an efficient approach while correctly handling edge cases such as empty arrays, duplicate values, negative numbers, sorted input, and very large inputs.

1. Array Fundamentals

What is an array?

An array is a collection of elements stored in an indexed structure. Elements can be accessed using their position, usually called an index.

const numbers = [10, 20, 30, 40];

console.log(numbers[0]); // 10
console.log(numbers[2]); // 30

What is the time complexity of accessing an array element?

Accessing an element by index is typically O(1). The position can be calculated directly from the index rather than requiring a sequential search.

What is the time complexity of searching an unsorted array?

A linear search may need to inspect every element, so the worst-case time complexity is O(n).

What is the difference between an array and a linked list?

Arrays provide efficient indexed access, while linked lists require traversal to reach an arbitrary position. Arrays can require shifting elements during insertion or deletion, whereas linked lists can modify links directly when the relevant node is already known.

2. Find the Largest and Smallest Element

How do you find the largest element in an array?

Traverse the array once while keeping track of the largest value encountered. This requires O(n) time and O(1) additional space.

function findMax(numbers) {
  if (numbers.length === 0) {
    return undefined;
  }

  let max = numbers[0];

  for (let i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
      max = numbers[i];
    }
  }

  return max;
}

console.log(findMax([12, 5, 28, 7, 19]));

How do you find the smallest element?

The same single-pass technique can be used by maintaining a minimum value instead of a maximum.

function findMin(numbers) {
  if (numbers.length === 0) {
    return undefined;
  }

  let min = numbers[0];

  for (let i = 1; i < numbers.length; i++) {
    if (numbers[i] < min) {
      min = numbers[i];
    }
  }

  return min;
}

console.log(findMin([12, 5, 28, 7, 19]));

3. Reverse an Array

How do you reverse an array without using another array?

Use two pointers. One starts at the beginning and the other at the end. Swap their values and move both pointers toward the center.

function reverseArray(numbers) {
  let left = 0;
  let right = numbers.length - 1;

  while (left < right) {
    [numbers[left], numbers[right]] =
      [numbers[right], numbers[left]];

    left++;
    right--;
  }

  return numbers;
}

console.log(reverseArray([1, 2, 3, 4, 5]));

The algorithm runs in O(n) time and uses O(1) additional space.

4. Find the Second Largest Element

How do you find the second largest distinct element?

Maintain both the largest and second-largest values while traversing the array once. The implementation should also decide how duplicate maximum values are treated.

function secondLargest(numbers) {
  let largest = -Infinity;
  let second = -Infinity;

  for (const value of numbers) {
    if (value > largest) {
      second = largest;
      largest = value;
    } else if (value > second && value < largest) {
      second = value;
    }
  }

  return second === -Infinity
    ? undefined
    : second;
}

console.log(secondLargest([10, 5, 20, 8, 20, 15]));

Here, the result is the second-largest distinct value. Always clarify whether duplicates should count as separate positions during an interview.

5. Remove Duplicates

How do you remove duplicate values from an array?

If preserving insertion order is required, a JavaScript Set provides a simple solution.

function removeDuplicates(numbers) {
  return [...new Set(numbers)];
}

console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5]));

This uses additional space proportional to the number of distinct values. In interviews, be prepared to discuss alternatives if extra space is not allowed.

6. Find Duplicate Elements

How do you find duplicates in an array?

A Set can track values that have already been encountered. If a value is already present, it is a duplicate.

function findDuplicates(numbers) {
  const seen = new Set();
  const duplicates = new Set();

  for (const value of numbers) {
    if (seen.has(value)) {
      duplicates.add(value);
    } else {
      seen.add(value);
    }
  }

  return [...duplicates];
}

console.log(findDuplicates([1, 3, 2, 3, 4, 2, 5]));

7. Two Sum Problem

How do you find two array elements whose sum equals a target?

A common efficient approach uses a hash map. For each value, calculate the complement required to reach the target and check whether that complement has already been encountered.

function twoSum(numbers, target) {
  const seen = new Map();

  for (let i = 0; i < numbers.length; i++) {
    const complement = target - numbers[i];

    if (seen.has(complement)) {
      return [seen.get(complement), i];
    }

    seen.set(numbers[i], i);
  }

  return [];
}

console.log(twoSum([2, 7, 11, 15], 9));

This approach runs in average O(n) time with O(n) additional space.

8. Move Zeros to the End

How do you move all zeros to the end while preserving the order of non-zero values?

Use a write pointer to place non-zero values at the front. After processing the array, fill the remaining positions with zeros.

function moveZeros(numbers) {
  let writeIndex = 0;

  for (const value of numbers) {
    if (value !== 0) {
      numbers[writeIndex++] = value;
    }
  }

  while (writeIndex < numbers.length) {
    numbers[writeIndex++] = 0;
  }

  return numbers;
}

console.log(moveZeros([0, 1, 0, 3, 12]));

This solution runs in O(n) time and uses O(1) additional space.

9. Find the Missing Number

How do you find a missing number from 0 to n?

If the array contains every number from 0 through n except one value, the expected sum can be compared with the actual sum.

function findMissing(numbers) {
  const n = numbers.length;
  const expected = (n * (n + 1)) / 2;

  let actual = 0;

  for (const value of numbers) {
    actual += value;
  }

  return expected - actual;
}

console.log(findMissing([3, 0, 1]));

This approach uses O(n) time and O(1) additional space, assuming the arithmetic remains safe for the input constraints.

10. Binary Search Questions

When can binary search be used?

Binary search can be used when the search space satisfies the ordering or monotonicity assumptions required by the specific binary-search formulation. The classic array version operates on sorted data.

function binarySearch(numbers, target) {
  let left = 0;
  let right = numbers.length - 1;

  while (left <= right) {
    const middle = Math.floor((left + right) / 2);

    if (numbers[middle] === target) {
      return middle;
    }

    if (numbers[middle] < target) {
      left = middle + 1;
    } else {
      right = middle - 1;
    }
  }

  return -1;
}

console.log(binarySearch([2, 4, 6, 8, 10, 12], 8));

The time complexity is O(log n) because each iteration eliminates roughly half of the remaining search space.

11. Find the First Repeating Element

How do you find the first value that appears more than once?

One approach is to scan from left to right while storing encountered values in a set. The first value already present in the set is the first repeating value by encounter order.

function firstRepeating(numbers) {
  const seen = new Set();

  for (const value of numbers) {
    if (seen.has(value)) {
      return value;
    }

    seen.add(value);
  }

  return undefined;
}

console.log(firstRepeating([5, 3, 4, 3, 5]));

12. Maximum Subarray Problem

What is the maximum subarray problem?

The maximum subarray problem asks for the contiguous subarray with the largest possible sum. A standard linear-time solution uses Kadane's algorithm.

function maxSubarraySum(numbers) {
  if (numbers.length === 0) {
    return 0;
  }

  let current = numbers[0];
  let best = numbers[0];

  for (let i = 1; i < numbers.length; i++) {
    current = Math.max(numbers[i], current + numbers[i]);
    best = Math.max(best, current);
  }

  return best;
}

console.log(maxSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4]));

Kadane's algorithm runs in O(n) time and O(1) additional space.

13. Rotate an Array

How do you rotate an array to the right by k positions?

An efficient in-place approach uses three reversals. First reverse the entire array, then reverse the first k elements and finally reverse the remaining elements.

function rotateRight(numbers, k) {
  const n = numbers.length;

  if (n === 0) {
    return numbers;
  }

  k %= n;

  reverse(numbers, 0, n - 1);
  reverse(numbers, 0, k - 1);
  reverse(numbers, k, n - 1);

  return numbers;
}

function reverse(numbers, left, right) {
  while (left < right) {
    [numbers[left], numbers[right]] =
      [numbers[right], numbers[left]];

    left++;
    right--;
  }
}

console.log(rotateRight([1, 2, 3, 4, 5], 2));

14. Merge Two Sorted Arrays

How do you merge two sorted arrays?

Use two pointers, one for each input array. Compare the pointed values and append the smaller value to the result. Continue until both arrays have been processed.

function mergeSortedArrays(first, second) {
  const result = [];
  let i = 0;
  let j = 0;

  while (i < first.length && j < second.length) {
    if (first[i] <= second[j]) {
      result.push(first[i++]);
    } else {
      result.push(second[j++]);
    }
  }

  while (i < first.length) {
    result.push(first[i++]);
  }

  while (j < second.length) {
    result.push(second[j++]);
  }

  return result;
}

console.log(
  mergeSortedArrays([1, 4, 7], [2, 3, 8])
);

The complexity is O(n + m), where n and m are the lengths of the two input arrays.

15. Two-Pointer Technique

What is the two-pointer technique?

The two-pointer technique maintains two indexes that move through an array according to the problem's conditions. It can reduce the need for nested loops and is particularly useful for sorted arrays, pairs, partitions, and in-place modifications.

A common example is checking whether a sorted array contains two values whose sum equals a target.

function hasPairWithSum(numbers, target) {
  let left = 0;
  let right = numbers.length - 1;

  while (left < right) {
    const sum = numbers[left] + numbers[right];

    if (sum === target) {
      return true;
    }

    if (sum < target) {
      left++;
    } else {
      right--;
    }
  }

  return false;
}

console.log(
  hasPairWithSum([1, 2, 4, 6, 8, 9], 10)
);

16. Sliding Window Questions

What is the sliding window technique?

Sliding window maintains a range of elements and moves that range through the array. Instead of recalculating information for every possible subarray, the algorithm updates the current window as it moves.

Find the maximum sum of a subarray of size k

function maxWindowSum(numbers, k) {
  if (k <= 0 || k > numbers.length) {
    return undefined;
  }

  let windowSum = 0;

  for (let i = 0; i < k; i++) {
    windowSum += numbers[i];
  }

  let best = windowSum;

  for (let i = k; i < numbers.length; i++) {
    windowSum += numbers[i];
    windowSum -= numbers[i - k];

    best = Math.max(best, windowSum);
  }

  return best;
}

console.log(maxWindowSum([2, 1, 5, 1, 3, 2], 3));

This approach runs in O(n) time instead of calculating every window independently.

17. Prefix Sum Questions

What is a prefix sum array?

A prefix sum array stores cumulative sums. It can make repeated range-sum queries efficient after an initial O(n) preprocessing step.

function buildPrefixSum(numbers) {
  const prefix = new Array(numbers.length + 1).fill(0);

  for (let i = 0; i < numbers.length; i++) {
    prefix[i + 1] = prefix[i] + numbers[i];
  }

  return prefix;
}

const prefix = buildPrefixSum([2, 4, 6, 8]);

console.log(prefix);

With this representation, a range sum from index left through right can be calculated using the difference between two prefix values.

18. Array Complexity Questions

Understanding array operation complexity is important during interviews. The exact complexity can depend on the implementation and the operation being performed.

Operation Typical Complexity
Access by index O(1)
Linear search O(n)
Binary search on sorted array O(log n)
Update by index O(1)
Insert at beginning O(n)
Delete from beginning O(n)
Traversal O(n)

19. How to Approach Array Interview Problems

When you receive an array problem, avoid immediately writing nested loops. First inspect the constraints and determine what structure or pattern can reduce unnecessary work.

  1. Clarify the input and expected output.
  2. Check whether the array is sorted or can be sorted.
  3. Identify whether duplicates are allowed.
  4. Look for a pair, subarray, range, or frequency pattern.
  5. Consider a hash map or set when fast lookup is required.
  6. Consider two pointers for ordered data or in-place operations.
  7. Consider sliding window for contiguous ranges.
  8. Consider prefix sums for repeated range calculations.
  9. Analyze time and space complexity before finalizing the solution.

20. Common Array Interview Mistakes

  • Accessing an index outside the valid range.
  • Forgetting to handle an empty array.
  • Using nested loops when a linear-time approach is possible.
  • Assuming an array is sorted when the problem does not guarantee it.
  • Ignoring duplicate values.
  • Modifying the input array when the problem expects the original data to remain unchanged.
  • Using extra memory without checking whether an in-place solution is required.
  • Failing to consider negative values.
  • Not reducing k using the array length in rotation problems.
  • Giving the correct output without being able to explain the complexity.

Key Takeaways

  • Arrays are fundamental to technical interview preparation.
  • Know array access, insertion, deletion, traversal, searching, and updating complexity.
  • Hash maps and sets can improve many lookup and duplicate-related problems.
  • Two-pointer techniques are useful for sorted arrays and in-place operations.
  • Sliding windows are useful for contiguous subarray problems.
  • Prefix sums can make repeated range-sum queries efficient.
  • Always clarify constraints, duplicates, ordering, and whether modifying the input is allowed.

Code Examples

function findMax(numbers) {
  if (numbers.length === 0) {
    return undefined;
  }

  let max = numbers[0];

  for (let i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
      max = numbers[i];
    }
  }

  return max;
}

console.log(findMax([12, 5, 28, 7, 19]));
    
function twoSum(numbers, target) {
  const seen = new Map();

  for (let i = 0; i < numbers.length; i++) {
    const complement = target - numbers[i];

    if (seen.has(complement)) {
      return [seen.get(complement), i];
    }

    seen.set(numbers[i], i);
  }

  return [];
}

console.log(twoSum([2, 7, 11, 15], 9));
    
function moveZeros(numbers) {
  let writeIndex = 0;

  for (const value of numbers) {
    if (value !== 0) {
      numbers[writeIndex++] = value;
    }
  }

  while (writeIndex < numbers.length) {
    numbers[writeIndex++] = 0;
  }

  return numbers;
}

console.log(moveZeros([0, 1, 0, 3, 12]));
    
function maxSubarraySum(numbers) {
  if (numbers.length === 0) {
    return 0;
  }

  let current = numbers[0];
  let best = numbers[0];

  for (let i = 1; i < numbers.length; i++) {
    current = Math.max(numbers[i], current + numbers[i]);
    best = Math.max(best, current);
  }

  return best;
}

console.log(
  maxSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4])
);
    
function binarySearch(numbers, target) {
  let left = 0;
  let right = numbers.length - 1;

  while (left <= right) {
    const middle = Math.floor((left + right) / 2);

    if (numbers[middle] === target) {
      return middle;
    }

    if (numbers[middle] < target) {
      left = middle + 1;
    } else {
      right = middle - 1;
    }
  }

  return -1;
}

console.log(
  binarySearch([2, 4, 6, 8, 10, 12], 8)
);
    
function mergeSortedArrays(first, second) {
  const result = [];
  let i = 0;
  let j = 0;

  while (i < first.length && j < second.length) {
    if (first[i] <= second[j]) {
      result.push(first[i++]);
    } else {
      result.push(second[j++]);
    }
  }

  while (i < first.length) {
    result.push(first[i++]);
  }

  while (j < second.length) {
    result.push(second[j++]);
  }

  return result;
}

console.log(
  mergeSortedArrays([1, 4, 7], [2, 3, 8])
);
    

Pro Tip

When solving an array interview problem, first identify the pattern instead of immediately coding. Look for sorting, hashing, two pointers, sliding windows, prefix sums, or in-place manipulation. Recognizing the right pattern often turns an O(n²) solution into O(n).

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.