ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Find First and Last Position of Element in Sorted Array

Swift

Goal -- WPM

Ready
Exercise Algorithm Area
1func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
2guard !nums.isEmpty else {
3return [-1, -1]
4}
5
6let first = findBoundary(nums, target, true)
7if first == -1 {
8return [-1, -1]
9}
10
11let last = findBoundary(nums, target, false)
12return [first, last]
13}
14
15func findBoundary(_ nums: [Int], _ target: Int, _ findFirst: Bool) -> Int {
16var low = 0
17var high = nums.count - 1
18var boundaryIndex = -1
19
20while low <= high {
21let mid = low + (high - low) / 2
22
23if nums[mid] == target {
24boundaryIndex = mid
25if findFirst {
26// Try to find an earlier occurrence
27high = mid - 1
28} else {
29// Try to find a later occurrence
30low = mid + 1
31}
32} else if nums[mid] < target {
33low = mid + 1
34} else {
35high = mid - 1
36}
37}
38
39// After the loop, if findFirst is true and boundaryIndex is valid, we need to ensure it's truly the first.
40// If findFirst is false and boundaryIndex is valid, we need to ensure it's truly the last.
41// The logic inside the loop already biases the search correctly.
42// However, if the target is not found at all, boundaryIndex will remain -1.
43// If findFirst is true and boundaryIndex is found, we might have overshot if the target was the very first element.
44// If findFirst is false and boundaryIndex is found, we might have undershot if the target was the very last element.
45// The current loop structure correctly handles this by continuing the search in the appropriate direction.
46// For example, if findFirst is true and we find target at mid, we set high = mid - 1. If the next mid is also target, we update boundaryIndex and repeat.
47// If the next mid is less than target, the loop terminates and boundaryIndex holds the last found target.
48// If the next mid is greater than target, the loop terminates and boundaryIndex holds the last found target.
49// This means boundaryIndex will always hold the index of the target that was found last during the biased search.
50
51// A final check is needed to ensure the found index is indeed the target, especially if the loop terminates without finding it.
52// However, the logic `if nums[mid] == target` ensures boundaryIndex is only set when the target is found.
53// If the target is not present, boundaryIndex remains -1.
54
55// Let's refine the logic for clarity and correctness.
56// The core idea is that when we find the target, we continue searching in the direction that might yield an earlier/later occurrence.
57// If `findFirst` is true, we want the smallest index. So, if `nums[mid] == target`, we record `mid` and try searching in the left half (`high = mid - 1`).
58// If `findFirst` is false, we want the largest index. So, if `nums[mid] == target`, we record `mid` and try searching in the right half (`low = mid + 1`).
59
60// The `boundaryIndex` will correctly store the index of the target that satisfies the condition (earliest or latest).
61// If the target is not found, `boundaryIndex` remains -1.
62
63return boundaryIndex
64}
Algorithm description viewbox

Find First and Last Position of Element in Sorted Array

Algorithm description:

This function finds the starting and ending positions of a given target value in a sorted array of integers. It utilizes a modified binary search algorithm to efficiently locate the first and last occurrences. This is useful in scenarios like searching for a specific version of a product in a sorted catalog or finding a range of timestamps in log data.

Algorithm explanation:

The `searchRange` function uses a helper function `findBoundary` twice, once to find the first occurrence and once to find the last. `findBoundary` implements a binary search. When the target is found at `mid`, it records `mid` as a potential boundary. If `findFirst` is true, it continues searching in the left half (`high = mid - 1`) to find an even earlier occurrence. If `findFirst` is false, it searches the right half (`low = mid + 1`) for a later occurrence. This process guarantees that `boundaryIndex` will hold the correct first or last index if the target exists. The time complexity is O(log n) because binary search is performed twice. The space complexity is O(1) as only a few variables are used. Edge cases include an empty array, the target not being present, and the target being at the boundaries of the array.

Pseudocode:

function searchRange(nums, target):
  if nums is empty:
    return [-1, -1]

  first_index = findBoundary(nums, target, true)
  if first_index is -1:
    return [-1, -1]

  last_index = findBoundary(nums, target, false)
  return [first_index, last_index]

function findBoundary(nums, target, findFirst):
  low = 0
  high = nums.length - 1
  boundaryIndex = -1

  while low <= high:
    mid = low + (high - low) / 2
    if nums[mid] == target:
      boundaryIndex = mid
      if findFirst:
        high = mid - 1 // search left for earlier
      else:
        low = mid + 1  // search right for later
    else if nums[mid] < target:
      low = mid + 1
    else:
      high = mid - 1

  return boundaryIndex