Bird
Raised Fist0
DSA C#programming~20 mins

First and Last Occurrence of Element in DSA C# - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
First and Last Occurrence Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Find first and last occurrence indexes in a sorted array
What is the output of the following C# code that finds the first and last occurrence of the number 3 in the array?
DSA C#
int[] arr = {1, 2, 3, 3, 3, 4, 5};
int first = Array.IndexOf(arr, 3);
int last = Array.LastIndexOf(arr, 3);
Console.WriteLine($"First: {first}, Last: {last}");
AFirst: 3, Last: 5
BFirst: 0, Last: 2
CFirst: 1, Last: 3
DFirst: 2, Last: 4
Attempts:
2 left
💡 Hint
Remember that Array.IndexOf returns the first index where the element appears, and Array.LastIndexOf returns the last index.
❓ Predict Output
intermediate
2:00remaining
Output of binary search for first occurrence
What will be the output of this C# code that uses binary search to find the first occurrence of 5 in a sorted array?
DSA C#
int[] arr = {1, 3, 5, 5, 5, 7, 9};
int target = 5;
int first = -1;
int low = 0, high = arr.Length - 1;
while (low <= high) {
    int mid = (low + high) / 2;
    if (arr[mid] == target) {
        first = mid;
        high = mid - 1;
    } else if (arr[mid] < target) {
        low = mid + 1;
    } else {
        high = mid - 1;
    }
}
Console.WriteLine(first);
A4
B3
C2
D-1
Attempts:
2 left
💡 Hint
Binary search narrows down to the first occurrence by moving high pointer.
🔧 Debug
advanced
2:30remaining
Why does this code fail to find last occurrence?
This C# code tries to find the last occurrence of 7 in a sorted array but enters an infinite loop. What is the reason?
DSA C#
int[] arr = {2, 4, 7, 7, 7, 8, 10};
int target = 7;
int last = -1;
int low = 0, high = arr.Length - 1;
while (low <= high) {
    int mid = (low + high) / 2;
    if (arr[mid] == target) {
        last = mid;
        low = mid + 1;  // <-- Problem here
    } else if (arr[mid] < target) {
        low = mid + 1;
    } else {
        high = mid - 1;
    }
}
Console.WriteLine(last);
AThe line 'low = mid - 1;' should be 'low = mid + 1;' to move right.
BThe line 'high = mid - 1;' should be 'high = mid + 1;' to move right.
CThe loop condition should be 'low < high' instead of 'low <= high'.
DThe variable 'last' should be initialized to 0 instead of -1.
Attempts:
2 left
💡 Hint
Think about how to move the search window to the right side after finding the target.
🧠 Conceptual
advanced
1:30remaining
Time complexity of finding first and last occurrence
What is the time complexity of finding the first and last occurrence of an element in a sorted array using binary search?
AO(n)
BO(log n)
CO(n log n)
DO(1)
Attempts:
2 left
💡 Hint
Binary search halves the search space each step.
🚀 Application
expert
3:00remaining
Find first and last occurrence in unsorted array efficiently
Given an unsorted array, which approach is the most efficient to find the first and last occurrence of a target element?
ATraverse the array once to record first and last indexes of the target.
BSort the array and then use binary search to find first and last occurrence.
CUse a hash map to store all indexes of elements, then get first and last for target.
DUse two separate linear scans: one from start for first occurrence, one from end for last occurrence.
Attempts:
2 left
💡 Hint
Think about the minimum passes needed over the array.

Practice

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

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find the first and last positions of a specific element in an array.
  2. 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.
  3. Final Answer:

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

    Positions of element = first and last occurrence [OK]
Hint: Look for positions of target element, not values or counts [OK]
Common Mistakes:
  • Confusing with finding max or min element
  • Trying to sum elements instead of finding positions
  • Counting unique elements instead of occurrences
2. Which of the following C# code snippets correctly initializes an array to find the first and last occurrence of an element?
easy
A. int arr = {1, 2, 3, 4, 5};
B. int arr = new int[5] {1, 2, 3, 4, 5};
C. int[] arr = new int[] {1, 2, 3, 4, 5};
D. int arr[] = new int[] {1, 2, 3, 4, 5};

Solution

  1. Step 1: Check array initialization syntax in C#

    Correct syntax is: int[] arr = new int[] {1, 2, 3, 4, 5};
  2. 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#.
  3. Final Answer:

    int[] arr = new int[] {1, 2, 3, 4, 5}; -> Option C
  4. Quick Check:

    Correct C# array syntax = int[] arr = new int[] {1, 2, 3, 4, 5}; [OK]
Hint: Use 'int[] arr = new int[] { ... }' for array initialization [OK]
Common Mistakes:
  • Using C/C++ style array declarations
  • Omitting 'new int[]' keyword
  • Assigning array size with initializer incorrectly
3. What will be the output of the following C# code?
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}");
medium
A. 3 1
B. 1 3
C. 0 4
D. -1 -1

Solution

  1. 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 skip
  2. Step 2: Print first and last

    first=1, last=3
  3. Final Answer:

    1 3 -> Option B
  4. Quick Check:

    First and last index of 3 = 1 and 3 [OK]
Hint: Track first when found, update last every time [OK]
Common Mistakes:
  • Swapping first and last indices
  • Not updating last occurrence correctly
  • Initializing first and last with wrong values
4. Identify the error in the following code that tries to find the first and last occurrence of an element:
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}");
medium
A. first and last are initialized incorrectly, causing wrong output
B. Loop condition should be i <= arr.Length
C. Target value is not assigned properly
D. Console.WriteLine syntax is incorrect

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    first and last are initialized incorrectly, causing wrong output -> Option A
  4. Quick Check:

    Initialize first to -1 and update only once [OK]
Hint: Initialize first to -1 and update only once [OK]
Common Mistakes:
  • Overwriting first occurrence index
  • Using wrong loop boundary
  • Incorrect Console.WriteLine format
5. Given a sorted array with possible duplicates, how can you efficiently find the first and last occurrence of a target element using C#?
hard
A. Use two binary searches: one for first occurrence, one for last occurrence
B. Traverse the array twice: once from start, once from end
C. Use a dictionary to store element counts
D. Sort the array again and find the target

Solution

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

    Sorted array allows binary search to find positions efficiently.
  2. 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.
  3. Step 3: Avoid full traversal or extra sorting

    Traversing twice or sorting again is inefficient. Dictionary counts do not give positions.
  4. Final Answer:

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

    Binary search twice = efficient first and last occurrence [OK]
Hint: Binary search twice for first and last occurrence in sorted array [OK]
Common Mistakes:
  • Using linear search on large sorted arrays
  • Sorting array again unnecessarily
  • Using dictionary counts instead of positions
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