Complete the code to find the first occurrence index of the target in the sorted array.
int FirstOccurrence(int[] nums, int target) {
int left = 0, right = nums.Length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
result = mid;
right = [1];
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}When we find the target, we move the right pointer to mid - 1 to continue searching on the left side for the first occurrence.
Complete the code to find the last occurrence index of the target in the sorted array.
int LastOccurrence(int[] nums, int target) {
int left = 0, right = nums.Length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
result = mid;
left = [1];
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}When we find the target, we move the left pointer to mid + 1 to continue searching on the right side for the last occurrence.
Fix the error in the code to count the occurrences of the target in the sorted array.
int CountOccurrences(int[] nums, int target) {
int first = FirstOccurrence(nums, target);
if (first == -1) return 0;
int last = LastOccurrence(nums, target);
return last - [1] + 1;
}The count is last index minus first index plus one. So we subtract first from last and add one.
Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.
var words = new List<string> {"apple", "bat", "carrot", "dog"};
var lengths = words.Where(word => word.Length > [1])
.ToDictionary(word => word, word => word.[2]);
We filter words longer than 3 characters and map each word to its Length property.
Fill all three blanks to create a dictionary of uppercase words and their lengths for words longer than 4 characters.
var words = new List<string> {"apple", "bat", "carrot", "dog"};
var result = words.Where(word => word.Length > [1])
.ToDictionary(word => word.[2](), word => word.[3]);
Filter words longer than 4 characters, use ToUpper() for keys, and Length for values.
