Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Count how many times a value occurs in a sorted array in O(log n).
Problem: Count how many times a value occurs in a sorted array in O(log n).
from bisect import bisect_left, bisect_right a = [2, 4, 4, 4, 4, 7, 9, 9] print(bisect_right(a, 4) - bisect_left(a, 4), bisect_right(a, 5) - bisect_left(a, 5), bisect_left(a, 9))What is printed?
- A. 4 0 7
- B. 4 0 6
- C. 3 0 6
- D. 4 1 6
Correct answer: B. 4 0 6
Occurrences = (first index > x) − (first index ≥ x). 4 occupies indices 1..4 → 4. 5 is absent so both bounds are 5 → 0. bisect_left(a, 9) is the first 9, index 6. Two binary searches: O(log n).
More Coding Interview Problems questions
- Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot. python def search(a, t): lo, hi =…
- Problem: Find the minimum of a rotated sorted array of distinct values. python def findmin(a): lo, hi = 0, len(a) - 1 while lo < hi: mid =…
- Problem: Packages with weights w (in order) must ship within D days; each day the ship carries a contiguous prefix of the remaining…
- Problem: A courier eats through n ≤ 10⁵ piles of parcels, pile sizes up to 10⁹, at speed k per hour (a pile smaller than k still takes a…
- Problem: Place c routers at given positions on a road so the minimum distance between any two routers is as large as possible. python def…
- Problem: The function below should return the integer square root ⌊√x⌋. java static int isqrt(int x) { int lo = 0, hi = x, ans = 0; while…