You are given a 0-indexed integer array nums and a positive integer k.

We call an index i k-big if the following conditions are satisfied:

  • There exist at least k different indices idx1 such that idx1 < i and nums[idx1] < nums[i].
  • There exist at least k different indices idx2 such that idx2 > i and nums[idx2] < nums[i].

Return the number of k-big indices.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,5,1,4], k = 2
Output: 1
💡 Note: Only index 2 (value 5) is k-big: it has 2 smaller elements on left [2,3] and 2 smaller elements on right [1,4]
Example 2 — No K-Big Indices
$ Input: nums = [1,1,1], k = 3
Output: 0
💡 Note: No index can have 3 smaller elements on both sides since all elements are equal and array has only 3 elements
Example 3 — Multiple K-Big Indices
$ Input: nums = [1,2,3,4,5,6], k = 1
Output: 4
💡 Note: Indices 1,2,3,4 are k-big: each has at least 1 smaller element on left and 1 smaller element on right

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Count the Number of K-Big Indices INPUT nums array (indices 0-4): 2 i=0 3 i=1 5 i=2 1 i=3 4 i=4 k = 2 K-big index condition: At least k smaller elements on LEFT and RIGHT Highlighted: index 2 (value 5) Potential k-big candidate ALGORITHM STEPS 1 Left Pass Count smaller elements to the left of each i i=0 i=1 i=2 i=3 i=4 0 1 2 0 2 2 Right Pass Count smaller elements to the right of each i i=0 i=1 i=2 i=3 i=4 1 1 2 0 0 3 Check Condition left[i] >= k AND right[i] >= k 4 Count Valid Only i=2: left=2, right=2 Both >= k=2 [OK] FINAL RESULT K-Big Index Analysis: i=0: L=0, R=1 --> NO i=1: L=1, R=1 --> NO i=2: L=2, R=2 --> OK i=3: L=0, R=0 --> NO i=4: L=2, R=0 --> NO OUTPUT 1 Only index 2 (value 5) is k-big with k=2 Key Insight: Use two passes with Binary Indexed Tree (BIT) or Balanced BST for efficient counting. First pass (left-to-right): count elements smaller than current on the left side. Second pass (right-to-left): count elements smaller on the right. Time: O(n log n) TutorialsPoint - Count the Number of K-Big Indices | Two-Pass Counting Approach
Asked in
Google 25 Amazon 18 Microsoft 15
8.5K Views
Medium Frequency
~25 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen