First and Last Occurrence of Element in DSA Typescript - Time & Space Complexity
We want to know how long it takes to find the first and last place a number appears in a list.
How does the time needed change when the list gets bigger?
Analyze the time complexity of the following code snippet.
function firstAndLastOccurrence(arr: number[], target: number): [number, number] {
let first = -1;
let last = -1;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
if (first === -1) first = i;
last = i;
}
}
return [first, last];
}
This code looks through the list once to find where the target number first and last appear.
- Primary operation: One loop that goes through each item in the list once.
- How many times: Exactly once for each item, so as many times as the list length.
As the list gets bigger, the time to check each item grows directly with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of steps grows evenly as the list grows.
Time Complexity: O(n)
This means the time needed grows in a straight line with the size of the list.
[X] Wrong: "Since we only want first and last, we can stop early and time is constant."
[OK] Correct: We must check every item to be sure the last occurrence is found, so time grows with list size.
Understanding how loops affect time helps you explain your code clearly and choose better methods when needed.
"What if the list was sorted? How would that change the time complexity of finding first and last occurrences?"
Practice
Solution
Step 1: Understand the problem statement
The problem asks to find the first and last index positions of a specific element in an array.Step 2: Identify what is required
We need to locate where the element appears first and last, not sums or counts.Final Answer:
The first and last positions where a given element appears -> Option CQuick Check:
First and last occurrence = positions of element [OK]
- Confusing occurrence with sum or max
- Thinking about unique elements instead
- Ignoring the order of elements
Solution
Step 1: Analyze the function parameters
The function should take an array of numbers and a target number to find.Step 2: Analyze the return type
We want to return two numbers (first and last index), so a tuple [number, number] is appropriate.Final Answer:
function findOccurrences(arr: number[], target: number): [number, number] -> Option DQuick Check:
Input array and target, output tuple of two indexes [OK]
- Using wrong input types like single number instead of array
- Returning only one number instead of two
- Returning array of wrong type
function findOccurrences(arr: number[], target: number): [number, number] {
let first = -1;
let last = -1;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
if (first === -1) first = i;
last = i;
}
}
return [first, last];
}
console.log(findOccurrences([5, 3, 7, 3, 9], 3));Solution
Step 1: Trace the loop to find first occurrence
At index 1, element is 3 which matches target, so first = 1.Step 2: Update last occurrence while looping
At index 3, element is 3 again, so last = 3.Final Answer:
[1, 3] -> Option AQuick Check:
First = 1, Last = 3 [OK]
- Returning first occurrence twice
- Returning indexes of wrong elements
- Not updating last occurrence properly
function findOccurrences(arr: number[], target: number): [number, number] {
let first = 0;
let last = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
if (first === 0) first = i;
last = i;
}
}
return [first, last];
}Solution
Step 1: Check initialization of first
first is set to 0, so if target is at index 0, condition first === 0 is true initially, causing incorrect logic.Step 2: Understand impact on first occurrence
If target is at index 0, first will never update correctly because first === 0 is true initially, so first stays 0 even if target not found.Final Answer:
first initialized to 0 causes wrong first occurrence when target is at index 0 -> Option BQuick Check:
Initialize first to -1 to fix [OK]
- Initializing first to 0 instead of -1
- Not handling target at index 0 correctly
- Assuming first occurrence is always > 0
Solution
Step 1: Understand the array is sorted
Since the array is sorted, binary search can be used to find elements efficiently.Step 2: Use binary search twice
One binary search finds the first occurrence, another finds the last occurrence, both in O(log n) time.Step 3: Compare with other options
Traversing is O(n), sorting again is unnecessary, hash map uses extra space and is less efficient.Final Answer:
Use two binary searches: one for first occurrence, one for last occurrence -> Option AQuick Check:
Binary search twice = efficient for sorted arrays [OK]
- Using linear search on sorted array
- Sorting array again unnecessarily
- Using extra space with hash map
Ready to prove it?
Pass the test and this pattern moves unknown
