702690. Count number of elements between two given elements in array

Basic

Count number of elements between two given elements in array

Summary

This problem involves counting the number of elements in an array that are between two given elements. The problem requires a basic understanding of arrays and hash data structures.

Detailed Explanation

The approach to solve this problem is to create a hash table where the keys are the array elements and the values are their corresponding indices. Then, we iterate through the array and for each element, we calculate its difference with the given elements (let's say, target1 and target2). If an element's difference with both targets is positive, it means that this element is between target1 and target2. We count the number of such elements and return the result.

Here's a step-by-step breakdown of the solution:

  1. Create a hash table where the keys are the array elements and the values are their corresponding indices.
  2. Iterate through the array and for each element, calculate its difference with both target1 and target2.
  3. If an element's difference with both targets is positive, increment a counter variable.
  4. Return the value of the counter variable.

Time complexity: O(n), where n is the number of elements in the array. This is because we're iterating through the array once.

Space complexity: O(n), as we're using a hash table to store the array elements and their indices.

Here's an ASCII art diagram illustrating the steps:

  +---------------+
  |    Array     |
  +---------------+
           |
           |
           v
  +---------------+
  | Hash Table   |
  | (keys: array  |
  |  elements,      |
  |  values: indices)|
  +---------------+
           |
           |
           v
  +---------------+
  | Iterate through  |
  | the array and    |
  | calculate diff.  |
  +---------------+
           |
           |
           v
  +---------------+
  | Count positive  |
  | differences     |
  +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static int countElements(int[] arr, int target1, int target2) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], i);
        }
        
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if ((arr[i] - target1) > 0 && (target2 - arr[i]) > 0) {
                count++;
            }
        }
        
        return count;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.