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) <= 1000
  • 1 <= heights[i] <= 1000

Step-by-step walkthrough

  1. Understand what counts as a mismatch

    We are given an integer list heights recording each person's height along a lineup from index 0 to len(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 i currently hold a different value from the height that belongs at slot i once the lineup is sorted:

    • Input: heights, a list of 1 to 1,000 integers, each between 1 and 1,000.
    • Output: an integer count between 0 and len(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 6 from the front to the back would fix the order, yet every index currently holds the wrong height, so the answer is 4.

  2. 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:

    1. 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 height 2 at the exact same indices. Because we compare numeric heights rather than individual identities, the target sequence is completely unique.
    2. We must sort a separate copy, not the input list. Calling heights.sort() mutates heights in place and erases the initial standing order; comparing heights with itself afterward would always yield 0. Calling target_heights = sorted(heights) allocates a fresh sorted list while keeping heights intact.
  3. Check whether sorting is fast enough

    Let's check the size bounds before coding. At most n = 1,000 elements appear in heights:

    • Sorting n integers takes O(n log n) comparisons—roughly 1,000 * 10 = 10,000 operations, finishing in well under a millisecond in Python.
    • Scanning both lists position by position takes one O(n) pass of at most 1,000 equality checks.

    Because height values also stay within 1 .. 1,000, a frequency-counting pass could avoid O(n log n) comparisons, which makes a great follow-up optimization for massive inputs. For n <= 1,000, sorted(heights) is fast, concise, and crystal clear.

  4. Compare both lineups position by position

    Once we compute target_heights = sorted(heights), both lists have identical length. We loop i across 0 .. len(heights) - 1 and add 1 to mismatch_count whenever heights[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_count
    
  5. Trace Example 1 step by step

    Let's trace heights = [2, 5, 2, 1, 4, 3]. Sorting a copy produces target_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 index 1 (5 != 2), both spots differ (mismatch_count reaches 2).
    • At index 2, height 2 already sits in one of the sorted 2 positions (2 == 2).
    • At index 3, 1 != 3 increments mismatch_count to 3.
    • At index 4, 4 == 4 matches, and at index 5, 3 != 5 brings mismatch_count to 4.

    The function returns 4.

  6. 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]:

  1. Create a separate sorted copy: target_heights = [1, 2, 2, 3].
  2. Check each index: i = 0 (3 != 1, count 1), i = 1 (1 != 2, count 2), i = 2 (2 == 2, match), i = 3 (2 != 3, count 3).
  3. Return 3.

Complexity

Let n be the length of heights.

  • Time: O(n log n). Creating target_heights runs Python's built-in comparison sort (a sorting algorithm that orders items by comparing pairs with < and <=), taking O(n log n) comparisons, followed by a single O(n) scan of constant-time index checks.
  • Space: O(n). target_heights stores a separate n-element list so the original heights order remains intact while we compare.

Edge cases

  • Single element ([7]): a 1-element list already matches its sorted copy, returning 0.
  • Already ordered with or without ties ([1, 2, 2, 3]): every index matches target_heights, returning 0.
  • All identical heights ([4, 4, 4, 4]): returns 0 because every spot holds 4 in both lists.
  • Strictly descending input ([5, 4, 3, 2, 1] vs. [4, 3, 2, 1]): for even n, all n positions mismatch; for odd n, the center element stays on the middle index and n - 1 positions mismatch ([5, 4, 3, 2, 1] yields 4).
  • Displaced duplicates ([2, 1, 2, 1, 2] vs. [1, 1, 2, 2, 2]): only indices 0 and 3 disagree, returning 2, because equal values are interchangeable.

Common mistakes

  • Mutating the input with heights.sort(): sorting heights in place erases the initial positions before the loop runs, so heights[i] != heights[i] is always false and the function returns 0.
  • Aliasing the list reference: writing target_heights = heights before target_heights.sort() points both names at the same list object in memory, triggering the exact same 0 bug.
  • 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 where K = 1,000 is 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. Since 1 <= heights[i] <= 1,000, we can count frequencies in an array of length 1,001 and stream the expected sorted height without building target_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 and O(n) extra memory. Because every height is an integer in 1 .. K with K = 1,000, counting sort (shown above) reduces the work to O(n + K) time and O(K) fixed space without allocating an n-element copy. Whenever n grows much larger than 1,000, that drops both runtime to O(n) and extra space to O(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 length n rather than the magnitude of the integers, so O(n log n) time and O(n) space work identically even for values up to 10^9 or 10^18. Array-based counting sort, by contrast, becomes impractical when K = 10^9 because allocating and scanning a billion-slot array wastes gigabytes of RAM; if only d distinct values appear, you could tally frequencies in a hash map and sort just the d unique keys in O(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 walk expected_height downward from 1,000 to 1 in counting sort). Note that subtracting the non-decreasing answer from n does not work: on [1, 2, 3], non-decreasing order has 0 mismatches whereas non-increasing order ([3, 2, 1]) has 2 mismatches because 2 remains at the middle index.

Follow-up questions

Similar questions

More Concentric Ai interview questions

All 3 Concentric Ai questions →