Magicsheet logo

Closest Equal Element Queries

Medium
87.5%
Updated 8/1/2025

Closest Equal Element Queries

What is this problem about?

The Closest Equal Element Queries coding problem typically involves an array and a set of queries. Each query provides an index, and you must find the nearest index (either to the left or right) that contains the same value as the element at the given index. If multiple such elements exist at the same distance, you usually return the smaller index or follow a specific tie-breaking rule defined in the problem.

Why is this asked in interviews?

Salesforce and other SaaS companies ask the Closest Equal Element Queries interview question to test your ability to preprocess data for efficient querying. This problem is a classic example of "Trade-off analysis": should you solve each query in O(N) time (slow), or should you spend time building a Hash Table or using Binary Search to answer queries in O(log N) or O(1) time?

Algorithmic pattern used

The most effective Array interview pattern for this problem involves a Hash Table combined with Binary Search. You can map each unique value in the array to a sorted list of indices where that value appears. To answer a query for value V at index I, you simply find the list for V in the hash table and use binary search (bisect or lower_bound) to find the position of I in that list. The closest elements will be the ones immediately before and after I in the sorted index list.

Example explanation

Array: [1, 5, 2, 5, 1, 5] Hash Table: {1: [0, 4], 5: [1, 3, 5], 2: [2]} Query: "Find closest equal element to index 3" (value is 5).

  1. Look up value 5 in map: [1, 3, 5].
  2. Find index 3 in the list.
  3. The neighbors of 3 are 1 and 5.
  4. Distances: |3 - 1| = 2, |3 - 5| = 2.
  5. Since distances are equal, return the smaller index 1.

Common mistakes candidates make

  • Brute Force: Iterating through the whole array for every query, resulting in O(N * Q) complexity.
  • Ignoring Sorted Property: Not realizing that the list of indices for a value is naturally sorted if you build it by traversing the array from left to right.
  • Off-by-one errors: Incorrectly handling the boundaries of the binary search.

Interview preparation tip

Whenever you see a problem with many queries on a static array, your first thought should be "How can I preprocess this?" Mapping values to lists of indices is a very powerful preprocessing technique.

Similar Questions