Data Structures & AlgorithmsModerateTCS NQT Digital · Infosys
Problem: Count the pairs (i, j) with i < j in the array [1, 5, 2, 8, 3, 5] whose absolute difference is at most 2.
- A. 3
- B. 6
- C. 1
- D. 12
Correct answer: B. 6
Sorting [1, 2, 3, 5, 5, 8] and sliding a window finds (1,2), (1,3), (2,3), (3,5), (3,5), (5,5): 6 pairs. Using < 2 gives 3, checking only adjacent positions in the original order gives 1, and counting ordered pairs gives 12.
More Coding Interview Problems questions
- Problem: A dice-throwing game: starting at 0, each throw adds a value from 1 to 6, and the player stops as soon as the total is at least…
- Problem: Dijkstra is run on a directed graph with arcs 0→1 (5), 0→2 (2), 2→1 (1), 1→3 (2), 2→3 (7), 3→4 (1), 2→4 (9). Each vertex is…
- Problem: A directed graph on vertices 0–4 has arcs 0→1, 1→2, 2→0, 2→3, 3→4. How many distinct simple directed cycles does it contain?
- Problem: An undirected graph on 6 vertices has edges 0-1, 1-2, 2-3, 3-0, 3-4, 4-5. Find the number of vertices whose removal leaves a…
- Problem: The rooted tree (root 0) has children 0: [1, 2], 1: [3, 4], 2: [5], 4: [6, 7], 5: [8]. Nodes are numbered in DFS pre-order with…
- Problem: A binary tree is given by a parent array where node i has parent p[i] (p[0] = −1 is the root): p = [−1, 0, 0, 1, 1, 2, 2, 5]. How…