for(int i=n-1; i>=0; i--) { if(arr[i] == x) return i; } return -1; searches from end, so it finds last occurrence. int i=0; while(arr[i] != x) i++; return i; may cause out-of-bound error if x not found. for(int i=0; i
Final Answer:
for(int i=0; i -> Option A
Quick Check:
Start to end loop with match check = for(int i=0; i
Hint: Loop from start, return index on first match [OK]
Common Mistakes:
Looping backward for first occurrence
Not handling element not found case
Returning wrong index when element differs
3. What will be the output of the following C code?
int arr[] = {2, 4, 6, 4, 8};
int n = 5, x = 4;
int first = -1, last = -1;
for(int i=0; i
medium
A. 1 3
B. 3 1
C. 0 4
D. -1 -1
Solution
Step 1: Trace the loop to find first and last occurrence
Hint: Track first when unset, update last on every match [OK]
Common Mistakes:
Swapping first and last values
Not updating last occurrence
Ignoring first occurrence initialization
4. Identify the error in the following code that tries to find the last occurrence of x in array arr of size n:
int lastOccurrence(int arr[], int n, int x) {
int last = -1;
for(int i=0; i
medium
A. Loop should run from n-1 to 0 for last occurrence
B. Using assignment (=) instead of comparison (==) in if condition
C. Variable last should be initialized to 0
D. Return statement should be inside the loop
Solution
Step 1: Check the if condition inside the loop
The condition uses single '=' which is assignment, not comparison. This causes wrong behavior.
Step 2: Correct the condition
It should be 'if(arr[i] == x)' to compare values properly.
Final Answer:
Using assignment (=) instead of comparison (==) in if condition -> Option B
Quick Check:
Use '==' for comparison, not '=' [OK]
Hint: Use '==' for comparison, '=' is assignment [OK]
Common Mistakes:
Using '=' instead of '==' in conditions
Loop direction confusion for last occurrence
Wrong initialization of variables
5. Given a sorted array arr of size n with possible duplicates, which approach is the most efficient to find the first and last occurrence of element x?
hard
A. Sort the array again and then find occurrences
B. Traverse the array from start to end once to find both occurrences
C. Use linear search twice: once from start, once from end
D. Use two binary searches: one for first occurrence, one for last occurrence
Solution
Step 1: Understand the array is sorted
Since the array is sorted, binary search can be used to find positions efficiently.
Step 2: Use binary search twice
One binary search finds the first occurrence by moving left on matches, another finds last occurrence by moving right on matches.
Final Answer:
Use two binary searches: one for first occurrence, one for last occurrence -> Option D