Mismatched Indices in a Height Lineup
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
An integer list heights records the measured height at each spot along a single file of people, indexed from 0 to len(heights) - 1. Ideally, the group should be arranged from shortest to tallest in non-decreasing order (equal heights may appear next to one another).
Determine how many positions i currently contain a height that differs from the height that belongs at position i once the entire list is sorted in non-decreasing order.
def count_height_mismatches(heights: List[int]) -> int:
Examples
Example 1
Input: heights = [2, 5, 2, 1, 4, 3]
Output: 4
Explanation: Sorting the list in non-decreasing order produces [1, 2, 2, 3, 4, 5]. Comparing spot by spot:
- Positions 2 (value 2) and 4 (value 4) already hold their sorted heights.
- Positions 0 (2 vs. 1), 1 (5 vs. 2), 3 (1 vs. 3), and 5 (3 vs. 5) hold different values, giving 4 mismatches.
Example 2
Input: heights = [6, 2, 3, 4]
Output: 4
Explanation: The non-decreasing arrangement is [2, 3, 4, 6]. Even though relocating 6 to the right end would fix the sequence, none of the four positions 0, 1, 2, 3 currently matches its target value (6 != 2, 2 != 3, 3 != 4, 4 != 6), so the answer is 4.
Constraints
1 <= len(heights) <= 10001 <= heights[i] <= 1000
Step-by-step walkthrough
Understand what counts as a mismatch
We are given an integer list
heightsrecording each person's height along a lineup from index0tolen(heights) - 1. The goal lineup puts everyone in non-decreasing order (from shortest to tallest, with equal heights allowed side by side).We need to count how many slots
icurrently hold a different value from the height that belongs at slotionce the lineup is sorted:- Input:
heights, a list of1to1,000integers, each between1and1,000. - Output: an integer count between
0andlen(heights).
Watch out for a common misreading: we are not counting the minimum number of swaps or the fewest people who need to move out of line. Look at Example 2 (
[6, 2, 3, 4]):index: 0 1 2 3 current row: [6, 2, 3, 4] sorted row: [2, 3, 4, 6] mismatch here? ^ ^ ^ ^ -> all 4 positions differ!Moving the single
6from the front to the back would fix the order, yet every index currently holds the wrong height, so the answer is4.- Input:
Why a sorted copy gives the unique target lineup
What does the lineup look like once everyone stands in non-decreasing order? Its height sequence is
sorted(heights). Two observations guarantee this is unambiguous:- Duplicate heights never create ambiguity. Suppose two people both have height
2. Regardless of which person takes the earlier spot, every valid non-decreasing arrangement places height2at the exact same indices. Because we compare numeric heights rather than individual identities, the target sequence is completely unique. - We must sort a separate copy, not the input list. Calling
heights.sort()mutatesheightsin place and erases the initial standing order; comparingheightswith itself afterward would always yield0. Callingtarget_heights = sorted(heights)allocates a fresh sorted list while keepingheightsintact.
- Duplicate heights never create ambiguity. Suppose two people both have height
Check whether sorting is fast enough
Let's check the size bounds before coding. At most
n = 1,000elements appear inheights:- Sorting
nintegers takesO(n log n)comparisons—roughly1,000 * 10 = 10,000operations, finishing in well under a millisecond in Python. - Scanning both lists position by position takes one
O(n)pass of at most1,000equality checks.
Because height values also stay within
1 .. 1,000, a frequency-counting pass could avoidO(n log n)comparisons, which makes a great follow-up optimization for massive inputs. Forn <= 1,000,sorted(heights)is fast, concise, and crystal clear.- Sorting
Compare both lineups position by position
Once we compute
target_heights = sorted(heights), both lists have identical length. We loopiacross0 .. len(heights) - 1and add1tomismatch_countwheneverheights[i] != target_heights[i].def count_height_mismatches(heights: List[int]) -> int: # Phase 1: Build the desired non-decreasing lineup in a separate list. # target_heights: sorted copy of heights, e.g. [1, 2, 2, 3, 4, 5]. # Why sorted() instead of heights.sort(): we must keep the original standing # order intact so we can compare both lineups position by position. target_heights = sorted(heights) # Phase 2: Count every floor index i where the current height differs from the target. mismatch_count = 0 for i in range(len(heights)): # Why != on heights is exact: students of equal height are interchangeable, # so every valid non-decreasing lineup has the exact same height at index i. if heights[i] != target_heights[i]: mismatch_count += 1 return mismatch_countTrace Example 1 step by step
Let's trace
heights = [2, 5, 2, 1, 4, 3]. Sorting a copy producestarget_heights = [1, 2, 2, 3, 4, 5]:index i: 0 1 2 3 4 5 heights[i]: 2 5 2 1 4 3 target_heights: 1 2 2 3 4 5 same height? NO NO yes NO yes NO mismatch_count: 1 2 2 3 3 4- At index
0(2 != 1) and index1(5 != 2), both spots differ (mismatch_countreaches2). - At index
2, height2already sits in one of the sorted2positions (2 == 2). - At index
3,1 != 3incrementsmismatch_countto3. - At index
4,4 == 4matches, and at index5,3 != 5bringsmismatch_countto4.
The function returns
4.- At index
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_height_mismatches(heights: List[int]) -> int: # Phase 1: Build the desired non-decreasing lineup in a separate list. # target_heights: sorted copy of heights, e.g. [1, 2, 2, 3, 4, 5]. # Why sorted() instead of heights.sort(): we must keep the original standing # order intact so we can compare both lineups position by position. target_heights = sorted(heights) # Phase 2: Count every floor index i where the current height differs from the target. mismatch_count = 0 for i in range(len(heights)): # Why != on heights is exact: students of equal height are interchangeable, # so every valid non-decreasing lineup has the exact same height at index i. if heights[i] != target_heights[i]: mismatch_count += 1 return mismatch_count✅ Submit now — all tests should pass.
Intuition & how it works
Imagine painting numbered spots 0, 1, 2, ... on the floor where a group is supposed to line up in non-decreasing order (each value is greater than or equal to the previous one, so equal heights can stand side by side). Instead of figuring out who traded places with whom, write down on a sheet of paper the exact height that belongs on each painted spot once everyone is sorted, then walk past the spots once and tally every spot where the current height disagrees with your sheet.
A common trap is trying to count adjacent inversions or the minimum number of people who must step out of line to fix the order, which answers a different question—in [6, 2, 3, 4], moving the single 6 to the right end repairs the whole row, yet all 4 floor spots currently hold the wrong value. Another pitfall is calling heights.sort(), an in-place sort (a sorting operation that overwrites the original list in memory and destroys its initial ordering), leaving you comparing the sorted list against itself and returning 0.
Here is a quick walkthrough on heights = [3, 1, 2, 2]:
- Create a separate sorted copy:
target_heights = [1, 2, 2, 3]. - Check each index:
i = 0(3 != 1, count1),i = 1(1 != 2, count2),i = 2(2 == 2, match),i = 3(2 != 3, count3). - Return
3.
Complexity
Let n be the length of heights.
- Time:
O(n log n). Creatingtarget_heightsruns Python's built-in comparison sort (a sorting algorithm that orders items by comparing pairs with<and<=), takingO(n log n)comparisons, followed by a singleO(n)scan of constant-time index checks. - Space:
O(n).target_heightsstores a separaten-element list so the originalheightsorder remains intact while we compare.
Edge cases
- Single element (
[7]): a 1-element list already matches its sorted copy, returning0. - Already ordered with or without ties (
[1, 2, 2, 3]): every index matchestarget_heights, returning0. - All identical heights (
[4, 4, 4, 4]): returns0because every spot holds4in both lists. - Strictly descending input (
[5, 4, 3, 2, 1]vs.[4, 3, 2, 1]): for evenn, allnpositions mismatch; for oddn, the center element stays on the middle index andn - 1positions mismatch ([5, 4, 3, 2, 1]yields4). - Displaced duplicates (
[2, 1, 2, 1, 2]vs.[1, 1, 2, 2, 2]): only indices0and3disagree, returning2, because equal values are interchangeable.
Common mistakes
- Mutating the input with
heights.sort(): sortingheightsin place erases the initial positions before the loop runs, soheights[i] != heights[i]is always false and the function returns0. - Aliasing the list reference: writing
target_heights = heightsbeforetarget_heights.sort()points both names at the same list object in memory, triggering the exact same0bug. - Computing minimum swaps or LIS complement: the task asks how many indices currently hold the wrong value, not the fewest moves needed to sort the list.
- Sorting in descending order: non-decreasing order goes from smallest to largest, not largest to smallest.
Alternative approaches
- Counting sort (
O(n + K)time,O(K)space whereK = 1,000is the maximum height). Counting sort is a non-comparison sorting method that tallies how often each integer appears in a fixed-size frequency array and then walks through the frequencies from smallest to largest. Since1 <= heights[i] <= 1,000, we can count frequencies in an array of length1,001and stream the expected sorted height without buildingtarget_heights:
```python def count_height_mismatches_counting(heights: list[int]) -> int: counts = [0] * 1001 for h in heights: counts[h] += 1
mismatch_count = 0
expected_height = 1
for h in heights:
while counts[expected_height] == 0:
expected_height += 1
if h != expected_height:
mismatch_count += 1
counts[expected_height] -= 1
return mismatch_count
```
Follow-up questions
- How much time and auxiliary memory does your implementation require, and how can you exploit the small height bound to run in linear time? Sorting a copy and scanning takes
O(n log n)time andO(n)extra memory. Because every height is an integer in1 .. KwithK = 1,000, counting sort (shown above) reduces the work toO(n + K)time andO(K)fixed space without allocating ann-element copy. Wheneverngrows much larger than1,000, that drops both runtime toO(n)and extra space toO(1). - Suppose individual heights could reach 10^9 instead of 1,000—how would that affect comparison sorting versus frequency counting? Comparison sorting with
sorted(heights)depends solely on the list lengthnrather than the magnitude of the integers, soO(n log n)time andO(n)space work identically even for values up to10^9or10^18. Array-based counting sort, by contrast, becomes impractical whenK = 10^9because allocating and scanning a billion-slot array wastes gigabytes of RAM; if onlyddistinct values appear, you could tally frequencies in a hash map and sort just thedunique keys inO(n + d log d)time. - What changes are needed if the target arrangement goes from tallest down to shortest rather than shortest up to tallest? Simply reverse the sort to
target_heights = sorted(heights, reverse=True)and keep the same index-by-index inequality loop (or walkexpected_heightdownward from1,000to1in counting sort). Note that subtracting the non-decreasing answer fromndoes not work: on[1, 2, 3], non-decreasing order has0mismatches whereas non-increasing order ([3, 2, 1]) has2mismatches because2remains at the middle index.
Follow-up questions
- How much time and auxiliary memory does your implementation require, and how can you exploit the small height bound to run in linear time?
- Suppose individual heights could reach 10^9 instead of 1,000—how would that affect comparison sorting versus frequency counting?
- What changes are needed if the target arrangement goes from tallest down to shortest rather than shortest up to tallest?
Similar questions
- Maximum Subset Gain Under an OR Threshold
- Optimal Meetup Coordinates for Weighted Grid Travel
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance