First and Last Occurrence of Element in DSA C# - 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.
int FirstOccurrence(int[] arr, int target) {
for (int i = 0; i < arr.Length; i++) {
if (arr[i] == target) return i;
}
return -1;
}
int LastOccurrence(int[] arr, int target) {
for (int i = arr.Length - 1; i >= 0; i--) {
if (arr[i] == target) return i;
}
return -1;
}
This code finds the first and last positions of a number in an array by checking elements one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array elements one by one.
- How many times: Up to n times for each function, where n is the array length.
As the list gets bigger, the number of checks grows roughly the same as the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The work grows directly with the size of the input list.
Time Complexity: O(n)
This means the time to find the first or last occurrence grows in a straight line with the list size.
[X] Wrong: "Since the array is sorted, we can find the first and last occurrence instantly."
[OK] Correct: Without using a special method like binary search, the code still checks elements one by one, so it takes time proportional to the list size.
Understanding how simple loops affect time helps you explain your code clearly and shows you know how to handle bigger data efficiently.
"What if we used binary search to find the first and last occurrence in a sorted array? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem statement
The problem asks to find the first and last positions of a specific element in an array.Step 2: Differentiate from other array queries
It is not about sums, max/min, or counting unique elements, but about positions of a target element.Final Answer:
The first and last positions where a given element appears -> Option DQuick Check:
Positions of element = first and last occurrence [OK]
- Confusing with finding max or min element
- Trying to sum elements instead of finding positions
- Counting unique elements instead of occurrences
Solution
Step 1: Check array initialization syntax in C#
Correct syntax is: int[] arr = new int[] {1, 2, 3, 4, 5};Step 2: Identify incorrect options
int arr = new int[5] {1, 2, 3, 4, 5}; has wrong syntax (cannot assign array with size and initializer like that), A is missing 'new int[]', D uses C-style syntax invalid in C#.Final Answer:
int[] arr = new int[] {1, 2, 3, 4, 5}; -> Option CQuick Check:
Correct C# array syntax = int[] arr = new int[] {1, 2, 3, 4, 5}; [OK]
- Using C/C++ style array declarations
- Omitting 'new int[]' keyword
- Assigning array size with initializer incorrectly
int[] arr = {5, 3, 7, 3, 9};
int target = 3;
int first = -1, last = -1;
for (int i = 0; i < arr.Length; i++) {
if (arr[i] == target) {
if (first == -1) first = i;
last = i;
}
}
Console.WriteLine($"{first} {last}");Solution
Step 1: Trace the loop to find first and last occurrence of 3
Array: [5, 3, 7, 3, 9]. Target = 3. Indices: 0 to 4.
i=0: arr[0]=5 !=3 skip
i=1: arr[1]=3 == target, first=-1 so first=1, last=1
i=2: arr[2]=7 !=3 skip
i=3: arr[3]=3 == target, first=1 (unchanged), last=3
i=4: arr[4]=9 !=3 skipStep 2: Print first and last
first=1, last=3Final Answer:
1 3 -> Option BQuick Check:
First and last index of 3 = 1 and 3 [OK]
- Swapping first and last indices
- Not updating last occurrence correctly
- Initializing first and last with wrong values
int[] arr = {2, 4, 2, 5, 2};
int target = 2;
int first = 0, last = 0;
for (int i = 0; i < arr.Length; i++) {
if (arr[i] == target) {
first = i;
last = i;
}
}
Console.WriteLine($"{first} {last}");Solution
Step 1: Analyze initialization of first and last
Both first and last start at 0. Inside loop, first and last are set to i every time target is found, so first will be overwritten and end up as last occurrence index.Step 2: Identify correct approach
First should be set only once when first occurrence is found (e.g., if first == -1). Last should update every time target is found.Final Answer:
first and last are initialized incorrectly, causing wrong output -> Option AQuick Check:
Initialize first to -1 and update only once [OK]
- Overwriting first occurrence index
- Using wrong loop boundary
- Incorrect Console.WriteLine format
Solution
Step 1: Understand the array is sorted with duplicates
Sorted array allows binary search to find positions efficiently.Step 2: Use binary search twice
One binary search finds the first occurrence by moving left when target found, another finds last occurrence by moving right.Step 3: Avoid full traversal or extra sorting
Traversing twice or sorting again is inefficient. Dictionary counts do not give positions.Final Answer:
Use two binary searches: one for first occurrence, one for last occurrence -> Option AQuick Check:
Binary search twice = efficient first and last occurrence [OK]
- Using linear search on large sorted arrays
- Sorting array again unnecessarily
- Using dictionary counts instead of positions
Ready to prove it?
Pass the test and this pattern moves unknown
