Find Element in Rotated Array

mediumcodingAlgorithmsBinary Search

Overview

A sorted array has been rotated at some unknown pivot. For example, [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2].

Given the rotated array and a target value, return the index of the target if it exists, or -1 if it does not.

Implement searchRotated(nums, target).

Constraints

  • All values in nums are unique.
  • The array was originally sorted in ascending order, then rotated.
  • Must achieve $O(\log n)$ time complexity — a linear scan is not acceptable.
  • nums may have length 0.

Examples

searchRotated([4, 5, 6, 7, 0, 1, 2], 0);  // 4
searchRotated([4, 5, 6, 7, 0, 1, 2], 3);  // -1
searchRotated([1], 0);                      // -1
searchRotated([1], 1);                      // 0

Notes

  • Modified binary search: at each step, one half of the array is always sorted. Determine which half is sorted and whether the target falls within that sorted range.
  • If the target falls in the sorted half, narrow search there; otherwise search the other half.
  • Edge cases: single element, target not present, array not rotated at all.

Solution

Reveal solution
function searchRotated(nums, target) {
  let lo = 0, hi = nums.length - 1;

  while (lo <= hi) {
    const mid = (lo + hi) >>> 1;
    if (nums[mid] === target) return mid;

    // Left half is sorted
    if (nums[lo] <= nums[mid]) {
      if (target >= nums[lo] && target < nums[mid]) {
        hi = mid - 1;
      } else {
        lo = mid + 1;
      }
    }
    // Right half is sorted
    else {
      if (target > nums[mid] && target <= nums[hi]) {
        lo = mid + 1;
      } else {
        hi = mid - 1;
      }
    }
  }

  return -1;
}

Resources

NameTopicDifficulty
Add BinaryAlgorithmseasyBalanced Binary TreeAlgorithmseasyBalanced BracketsAlgorithmseasyBinary SearchAlgorithmseasyBinary Search Tree Lowest Common AncestorAlgorithmseasyBinary Tree Maximum DepthAlgorithmseasyBinary Tree SubtreeAlgorithmseasyBit CountingAlgorithmseasyBit ReversalAlgorithmseasyCount Set Bits in a Binary NumberAlgorithmseasyDiameter of Binary TreeAlgorithmseasyFind Duplicates in ArrayAlgorithmseasyFirst Bad VersionAlgorithmseasyFlip Binary TreeAlgorithmseasyFlood FillAlgorithmseasyLinked List Detect CycleAlgorithmseasyLinked List ReversalAlgorithmseasyLinked Lists Combine Two SortedAlgorithmseasyLongest PalindromeAlgorithmseasyMiddle of the Linked ListAlgorithmseasyMost Common ElementsAlgorithmseasyOptimal Stock TradingAlgorithmseasyPair SumAlgorithmseasyRansom NoteAlgorithmseasyStaircase Climbing CombinationsAlgorithmseasyString AnagramAlgorithmseasyString PalindromeAlgorithmseasy01 MatrixAlgorithmsmediumAccounts MergeAlgorithmsmediumArray Product Excluding CurrentAlgorithmsmediumBinary Search Tree Kth Smallest ElementAlgorithmsmediumBinary Tree Level Order TraversalAlgorithmsmediumBinary Tree Rebuilding from Preorder and Inorder TraversalsAlgorithmsmediumBinary Tree Right Side ViewAlgorithmsmediumCombinations for Target SumAlgorithmsmediumCount Islands in a GridAlgorithmsmediumCourse DependencyAlgorithmsmediumDecode MessageAlgorithmsmediumDisjoint IntervalsAlgorithmsmediumDistinct Paths in GridAlgorithmsmediumEvaluate Reverse Polish NotationAlgorithmsmediumFind All Anagrams in a StringAlgorithmsmediumFind Element in Rotated ArrayAlgorithmsmediumFind the Longest Palindromic SubstringAlgorithmsmediumFind Word in GridAlgorithmsmediumGraph CloneAlgorithmsmediumGraph Count Connected ComponentsAlgorithmsmediumIs the Graph a TreeAlgorithmsmediumK Closest Points to OriginAlgorithmsmediumLetter Combinations of a Phone NumberAlgorithmsmediumLongest Increasing SubsequenceAlgorithmsmediumLongest Non-repeating SubstringAlgorithmsmediumLongest Repeating Substring After ReplacementsAlgorithmsmediumLowest Common Ancestor of a Binary TreeAlgorithmsmediumMatrix RotationAlgorithmsmediumMatrix Spiral TraversalAlgorithmsmediumMatrix ZeroingAlgorithmsmediumMaximum Sum in Contiguous ArrayAlgorithmsmediumMaximum Water Trapped Between WallsAlgorithmsmediumMerge New IntervalAlgorithmsmediumMerge Overlapping IntervalsAlgorithmsmediumMinimum Coins for ChangeAlgorithmsmediumMinimum Height TreesAlgorithmsmediumPalindromic SubstringsAlgorithmsmediumPartition Equal Subset SumAlgorithmsmediumPermutationsAlgorithmsmediumRotting OrangesAlgorithmsmediumSegment WordsAlgorithmsmediumSort ColorsAlgorithmsmediumString Anagram GroupsAlgorithmsmediumString to Integer (atoi)AlgorithmsmediumSubsetsAlgorithmsmediumSum Without AdditionAlgorithmsmediumTask CoordinationAlgorithmsmediumTrie (Prefix Tree)AlgorithmsmediumTriplet SumAlgorithmsmediumValidate Binary Search TreeAlgorithmsmediumBasic CalculatorAlgorithmshardBinary Tree EqualAlgorithmshardBinary Tree Maximum Total PathAlgorithmshardDelete Nth Node from End of Linked ListAlgorithmshardEnd of Array ReachableAlgorithmshardExtraterrestrial LanguageAlgorithmshardFind Missing Number in SequenceAlgorithmshardFind Words in GridAlgorithmshardLargest Rectangle in HistogramAlgorithmshardLinked Lists Combine K SortedAlgorithmshardLongest Common SubsequenceAlgorithmshardLongest Consecutive Number SequenceAlgorithmshardMaximum Product in Contiguous ArrayAlgorithmshardMaximum Profit in Job SchedulingAlgorithmshardMeeting CalendarAlgorithmshardMinimum Meeting Rooms NeededAlgorithmshardNeighborhood TheftAlgorithmshardNeighborhood Theft (Circular)AlgorithmshardNumber Stream MedianAlgorithmshardOcean FlowAlgorithmshardRearrange Linked ListAlgorithmshardShortest Substring Containing CharactersAlgorithmshardSmallest Element in Rotated Sorted ArrayAlgorithmshardTrapping Rain WaterAlgorithmshardWord FinderAlgorithmshardWord LadderAlgorithmshard
103 of 103 problems