Bird
Raised Fist0
DSA Rustprogramming~5 mins

First and Last Occurrence of Element in DSA Rust - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: First and Last Occurrence of Element
O(log n)
Understanding Time Complexity

We want to know how long it takes to find the first and last positions of a number in a list.

How does the time needed change when the list gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn first_occurrence(arr: &[i32], target: i32) -> Option {
    let mut left = 0;
    let mut right = arr.len();
    while left < right {
        let mid = (left + right) / 2;
        if arr[mid] >= target {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    if left < arr.len() && arr[left] == target {
        Some(left)
    } else {
        None
    }
}

fn last_occurrence(arr: &[i32], target: i32) -> Option {
    let mut left = 0;
    let mut right = arr.len();
    while left < right {
        let mid = (left + right) / 2;
        if arr[mid] <= target {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    if right > 0 && arr[right - 1] == target {
        Some(right - 1)
    } else {
        None
    }
}

This code finds the first and last positions of a target number in a sorted list using a method called binary search.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop that halves the search range each time.
  • How many times: The loop runs about log2 of the list size times.
How Execution Grows With Input

Each time the list size doubles, the number of steps increases by one.

Input Size (n)Approx. Operations
10About 4 steps
100About 7 steps
1000About 10 steps

Pattern observation: The steps grow slowly as the list grows, adding only one step when the list size doubles.

Final Time Complexity

Time Complexity: O(log n)

This means the time to find the first or last occurrence grows slowly, increasing by one step each time the list size doubles.

Common Mistake

[X] Wrong: "Since we search twice (first and last), the time is double, so O(2n)."

[OK] Correct: Each search is O(log n), and doing two searches is still O(log n) because constants are ignored in big-O.

Interview Connect

Knowing how to find positions quickly in sorted data is a key skill. It shows you understand efficient searching and can handle real-world data problems calmly.

Self-Check

"What if the list was not sorted? How would the time complexity change for finding first and last occurrences?"

Practice

(1/5)
1. What does the "First and Last Occurrence of Element" problem ask you to find in a list?
easy
A. The first and last positions where a given element appears
B. The sum of all elements in the list
C. The maximum and minimum values in the list
D. The number of unique elements in the list

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find the first and last positions of a specific element in a list.
  2. Step 2: Identify what is required

    We need to locate the earliest and latest index where the element appears.
  3. Final Answer:

    The first and last positions where a given element appears -> Option A
  4. Quick Check:

    Positions = first and last occurrence [OK]
Hint: Look for earliest and latest index of element [OK]
Common Mistakes:
  • Confusing with sum or count of elements
  • Looking for max/min values instead
  • Ignoring the order of occurrences
2. Which Rust code snippet correctly finds the first occurrence index of element target in vector v?
easy
A. v.iter().position(|&x| x == target)
B. v.iter().find(|&&x| x == target)
C. v.iter().filter(|&&x| x == target).count()
D. v.iter().last().position(|&x| x == target)

Solution

  1. Step 1: Understand Rust iterator methods

    The position method returns the index of the first element matching the condition.
  2. Step 2: Check each option

    v.iter().position(|&x| x == target) uses position correctly to find the first occurrence index. v.iter().find(|&&x| x == target) returns an Option<&T>, not index. v.iter().filter(|&&x| x == target).count() counts matches, not index. v.iter().last().position(|&x| x == target) is invalid because last() returns an element, not an iterator.
  3. Final Answer:

    v.iter().position(|&x| x == target) -> Option A
  4. Quick Check:

    position() returns first index [OK]
Hint: Use .position() to get first index [OK]
Common Mistakes:
  • Using find() which returns element, not index
  • Using count() which returns number of matches
  • Trying to call position() after last() which is invalid
3. What is the output of this Rust code?
let v = vec![2, 3, 5, 3, 7];
let target = 3;
let first = v.iter().position(|&x| x == target);
let last = v.iter().rposition(|&x| x == target);
println!("[{:?}, {:?}]", first, last);
medium
A. [Some(2), Some(3)]
B. [Some(1), Some(4)]
C. [None, None]
D. [Some(1), Some(3)]

Solution

  1. Step 1: Find first occurrence of 3 in vector

    Vector is [2, 3, 5, 3, 7]. The first 3 is at index 1.
  2. Step 2: Find last occurrence of 3 in vector

    The last 3 is at index 3.
  3. Final Answer:

    [Some(1), Some(3)] -> Option D
  4. Quick Check:

    First = 1, Last = 3 [OK]
Hint: Use position() and rposition() for first and last [OK]
Common Mistakes:
  • Confusing indices of first and last occurrences
  • Using wrong iterator methods
  • Forgetting that indices start at 0
4. Identify the error in this Rust code that tries to find the last occurrence of target in vector v:
let last = v.iter().position(|&x| x == target).unwrap();
println!("{}", last);
medium
A. unwrap() causes panic if element not found
B. v.iter() cannot be used with position()
C. Using position() finds first, not last occurrence
D. Missing semicolon after unwrap()

Solution

  1. Step 1: Understand what position() returns

    position() returns the index of the first element matching the condition, not the last.
  2. Step 2: Identify correct method for last occurrence

    To find the last occurrence, rposition() should be used instead of position().
  3. Final Answer:

    Using position() finds first, not last occurrence -> Option C
  4. Quick Check:

    position() = first occurrence, not last [OK]
Hint: Use rposition() for last occurrence, not position() [OK]
Common Mistakes:
  • Using position() for last occurrence
  • Ignoring unwrap() panic possibility
  • Thinking iter() can't use position()
5. Given a sorted vector v with possible duplicates, which approach efficiently finds the first and last occurrence of target using binary search in Rust?
hard
A. Use find() method twice with different closures
B. Use two binary searches: one for first occurrence, one for last occurrence
C. Use a single linear scan from start to end
D. Use position() and rposition() on the entire vector

Solution

  1. Step 1: Understand the vector is sorted with duplicates

    Binary search can be used to find positions efficiently in sorted data.
  2. Step 2: Use two binary searches for first and last occurrence

    One binary search finds the first index where target appears, another finds the last index.
  3. Final Answer:

    Use two binary searches: one for first occurrence, one for last occurrence -> Option B
  4. Quick Check:

    Binary search twice for first and last [OK]
Hint: Binary search twice for first and last occurrence [OK]
Common Mistakes:
  • Using linear scan on large sorted vector
  • Using position() which is linear time
  • Trying to find both occurrences in one binary search
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard