{"id":"6b093ddfbd4755deb67ee098","slug":"rotated-array-search","title":"Search in a rotated array","summary":"Someone \"turned\" a sorted array at an unknown point. Find an element in O(log n) – binary search that recognises the sorted half at every step.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["binary-search","arrays","divide-and-conquer"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** Index of target in a rotated sorted array of distinct values, or -1. Must be O(log n). */\nfunction searchRotated(nums: ArrayLike<number>, target: number): number {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"function rotated(n, shift, start = 0) {\n  return Array.from({ length: n }, (_, i) => start + ((i + shift) % n) * 2);\n}\n\nfunction counting(values) {\n  const stats = { reads: 0 };\n  const proxy = new Proxy(values, {\n    get(target, prop, receiver) {\n      if (typeof prop === 'string' && /^\\d+$/.test(prop)) stats.reads++;\n      return Reflect.get(target, prop, receiver);\n    },\n  });\n  return { proxy, stats };\n}\n\ntest('finds elements in both parts', () => {\n  expect(searchRotated([4, 5, 6, 7, 0, 1, 2], 0)).toBe(4);\n  expect(searchRotated([4, 5, 6, 7, 0, 1, 2], 5)).toBe(1);\n  expect(searchRotated([4, 5, 6, 7, 0, 1, 2], 3)).toBe(-1);\n});\n\ntest('array that is not rotated', () => {\n  expect(searchRotated([1, 2, 3, 4, 5], 4)).toBe(3);\n  expect(searchRotated([1, 2, 3, 4, 5], 6)).toBe(-1);\n});\n\ntest('tiny arrays', () => {\n  expect(searchRotated([], 7)).toBe(-1);\n  expect(searchRotated([1], 1)).toBe(0);\n  expect(searchRotated([1], 0)).toBe(-1);\n  expect(searchRotated([3, 1], 1)).toBe(1);\n  expect(searchRotated([3, 1], 3)).toBe(0);\n  expect(searchRotated([1, 3], 3)).toBe(1);\n});\n\ntest('rotation point at the edges', () => {\n  expect(searchRotated([2, 3, 4, 5, 1], 1)).toBe(4);\n  expect(searchRotated([5, 1, 2, 3, 4], 5)).toBe(0);\n});\n\ntest('every element of every rotation', () => {\n  for (let n = 1; n <= 12; n++) {\n    for (let shift = 0; shift < n; shift++) {\n      const nums = rotated(n, shift, -10);\n      nums.forEach((v, i) => expect(searchRotated(nums, v)).toBe(i));\n      expect(searchRotated(nums, -11)).toBe(-1);\n      expect(searchRotated(nums, -9)).toBe(-1);\n      expect(searchRotated(nums, 100)).toBe(-1);\n    }\n  }\n});\n\ntest('reads only O(log n) elements', () => {\n  const { proxy, stats } = counting(rotated(4096, 1234));\n  for (const target of [0, 2468, 8190, 1, 9999]) {\n    stats.reads = 0;\n    searchRotated(proxy, target);\n    expect(stats.reads).toBeLessThanOrEqual(100);\n  }\n});\n\ntest('performance: 100 000 searches in 1 000 000 elements', () => {\n  const n = 1000000;\n  const nums = rotated(n, 777777);\n  let found = 0;\n  for (let i = 0; i < 100000; i++) {\n    const target = (i * 7919) % (2 * n);\n    const idx = searchRotated(nums, target);\n    if (target % 2 === 0) {\n      if (nums[idx] === target) found++;\n    } else if (idx !== -1) found = -Infinity;\n  }\n  expect(found).toBe(50000);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Index of target in a rotated sorted array of distinct values, or -1. Must be O(log n).\n * @param {number[]} nums\n * @param {number} target\n * @returns {number}\n */\nfunction searchRotated(nums, target) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"function rotated(n, shift, start = 0) {\n  return Array.from({ length: n }, (_, i) => start + ((i + shift) % n) * 2);\n}\n\nfunction counting(values) {\n  const stats = { reads: 0 };\n  const proxy = new Proxy(values, {\n    get(target, prop, receiver) {\n      if (typeof prop === 'string' && /^\\d+$/.test(prop)) stats.reads++;\n      return Reflect.get(target, prop, receiver);\n    },\n  });\n  return { proxy, stats };\n}\n\ntest('finds elements in both parts', () => {\n  expect(searchRotated([4, 5, 6, 7, 0, 1, 2], 0)).toBe(4);\n  expect(searchRotated([4, 5, 6, 7, 0, 1, 2], 5)).toBe(1);\n  expect(searchRotated([4, 5, 6, 7, 0, 1, 2], 3)).toBe(-1);\n});\n\ntest('array that is not rotated', () => {\n  expect(searchRotated([1, 2, 3, 4, 5], 4)).toBe(3);\n  expect(searchRotated([1, 2, 3, 4, 5], 6)).toBe(-1);\n});\n\ntest('tiny arrays', () => {\n  expect(searchRotated([], 7)).toBe(-1);\n  expect(searchRotated([1], 1)).toBe(0);\n  expect(searchRotated([1], 0)).toBe(-1);\n  expect(searchRotated([3, 1], 1)).toBe(1);\n  expect(searchRotated([3, 1], 3)).toBe(0);\n  expect(searchRotated([1, 3], 3)).toBe(1);\n});\n\ntest('rotation point at the edges', () => {\n  expect(searchRotated([2, 3, 4, 5, 1], 1)).toBe(4);\n  expect(searchRotated([5, 1, 2, 3, 4], 5)).toBe(0);\n});\n\ntest('every element of every rotation', () => {\n  for (let n = 1; n <= 12; n++) {\n    for (let shift = 0; shift < n; shift++) {\n      const nums = rotated(n, shift, -10);\n      nums.forEach((v, i) => expect(searchRotated(nums, v)).toBe(i));\n      expect(searchRotated(nums, -11)).toBe(-1);\n      expect(searchRotated(nums, -9)).toBe(-1);\n      expect(searchRotated(nums, 100)).toBe(-1);\n    }\n  }\n});\n\ntest('reads only O(log n) elements', () => {\n  const { proxy, stats } = counting(rotated(4096, 1234));\n  for (const target of [0, 2468, 8190, 1, 9999]) {\n    stats.reads = 0;\n    searchRotated(proxy, target);\n    expect(stats.reads).toBeLessThanOrEqual(100);\n  }\n});\n\ntest('performance: 100 000 searches in 1 000 000 elements', () => {\n  const n = 1000000;\n  const nums = rotated(n, 777777);\n  let found = 0;\n  for (let i = 0; i < 100000; i++) {\n    const target = (i * 7919) % (2 * n);\n    const idx = searchRotated(nums, target);\n    if (target % 2 === 0) {\n      if (nums[idx] === target) found++;\n    } else if (idx !== -1) found = -Infinity;\n  }\n  expect(found).toBe(50000);\n});\n"},{"lang":"python","runner":"browser","starter":"from typing import Sequence\n\n\ndef search_rotated(nums: Sequence[int], target: int) -> int:\n    \"\"\"Index of target in a rotated sorted sequence of distinct values, or -1. Must be O(log n).\n    nums supports len() and indexing (it may be a list or a read-only sequence).\"\"\"\n    raise NotImplementedError\n","testCount":7,"tests":"def rotated(n, shift, start=0):\n    return [start + ((i + shift) % n) * 2 for i in range(n)]\n\n\nclass Probe:\n    \"\"\"A read-only sequence that counts element reads.\"\"\"\n\n    def __init__(self, values):\n        self._values = values\n        self.reads = 0\n\n    def __len__(self):\n        return len(self._values)\n\n    def __getitem__(self, i):\n        self.reads += 1\n        return self._values[i]\n\n\ndef check(nums, target, expected):\n    got = search_rotated(nums, target)\n    assert got == expected, f\"search_rotated({list(nums)[:10]}, {target}): expected {expected}, got {got}\"\n\n\ndef test_finds_elements_in_both_parts():\n    check([4, 5, 6, 7, 0, 1, 2], 0, 4)\n    check([4, 5, 6, 7, 0, 1, 2], 5, 1)\n    check([4, 5, 6, 7, 0, 1, 2], 3, -1)\n\n\ndef test_array_that_is_not_rotated():\n    check([1, 2, 3, 4, 5], 4, 3)\n    check([1, 2, 3, 4, 5], 6, -1)\n\n\ndef test_tiny_arrays():\n    check([], 7, -1)\n    check([1], 1, 0)\n    check([1], 0, -1)\n    check([3, 1], 1, 1)\n    check([3, 1], 3, 0)\n    check([1, 3], 3, 1)\n\n\ndef test_rotation_point_at_the_edges():\n    check([2, 3, 4, 5, 1], 1, 4)\n    check([5, 1, 2, 3, 4], 5, 0)\n\n\ndef test_every_element_of_every_rotation():\n    for n in range(1, 13):\n        for shift in range(n):\n            nums = rotated(n, shift, -10)\n            for i, v in enumerate(nums):\n                check(nums, v, i)\n            for missing in (-11, -9, 100):\n                check(nums, missing, -1)\n\n\ndef test_reads_only_log_n_elements():\n    probe = Probe(rotated(4096, 1234))\n    for target in (0, 2468, 8190, 1, 9999):\n        probe.reads = 0\n        search_rotated(probe, target)\n        assert probe.reads <= 100, f\"target {target}: {probe.reads} reads, expected at most 100\"\n\n\ndef test_performance_10k_searches_in_1m():\n    n = 1_000_000\n    nums = rotated(n, 777_777)\n    found = 0\n    for i in range(10_000):\n        target = (i * 7919) % (2 * n)\n        idx = search_rotated(nums, target)\n        if target % 2 == 0:\n            assert nums[idx] == target, f\"target {target}: got index {idx}\"\n            found += 1\n        else:\n            assert idx == -1, f\"target {target} is absent, got {idx}\"\n    assert found == 5000, f\"found {found}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\n\npublic static class Solution\n{\n    /// <summary>Index of target in a rotated sorted array of distinct values, or -1. Must be O(log n).</summary>\n    public static int SearchRotated(int[] nums, int target)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":6},{"lang":"java","runner":"judge0","starter":"class Solution {\n    /** Index of target in a rotated sorted array of distinct values, or -1. Must be O(log n). */\n    static int searchRotated(int[] nums, int target) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":6},{"lang":"go","runner":"judge0","starter":"package main\n\n// SearchRotated returns the index of target in a rotated sorted slice of distinct values, or -1.\n// Must be O(log n).\nfunc SearchRotated(nums []int, target int) int {\n\tpanic(\"not implemented\")\n}\n","testCount":6}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:55.487Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A ring buffer of event IDs stores them in ascending order, but once full it starts from the beginning again – so memory holds a sorted array "},{"type":"text","text":"rotated","marks":[{"type":"bold"}]},{"type":"text","text":" at an unknown point, e.g. "},{"type":"text","text":"[40, 50, 60, 70, 10, 20, 30]","marks":[{"type":"code"}]},{"type":"text","text":". Find the position of the event with a given ID."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"The function gets an array "},{"type":"text","text":"nums","marks":[{"type":"code"}]},{"type":"text","text":" of "},{"type":"text","text":"distinct","marks":[{"type":"bold"}]},{"type":"text","text":" integers (sorted ascending, then rotated by any number of positions, possibly zero) and a value "},{"type":"text","text":"target","marks":[{"type":"code"}]},{"type":"text","text":". Return the index of "},{"type":"text","text":"target","marks":[{"type":"code"}]},{"type":"text","text":" in "},{"type":"text","text":"nums","marks":[{"type":"code"}]},{"type":"text","text":", or "},{"type":"text","text":"-1","marks":[{"type":"code"}]},{"type":"text","text":" when it is absent."}]},{"type":"paragraph","content":[{"type":"text","text":"The solution has to run in "},{"type":"text","text":"O(log n)","marks":[{"type":"bold"}]},{"type":"text","text":" time – the tests count element reads (in JS/TS and Python the array is sometimes replaced by an object supporting only length and indexing) and run a hundred thousand searches in an array of a million elements."}]},{"type":"paragraph","content":[{"type":"text","text":"Signatures: "},{"type":"text","text":"searchRotated(nums, target)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"search_rotated(nums, target)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.SearchRotated","marks":[{"type":"code"}]},{"type":"text","text":" (C#), "},{"type":"text","text":"Solution.searchRotated","marks":[{"type":"code"}]},{"type":"text","text":" (Java), "},{"type":"text","text":"SearchRotated","marks":[{"type":"code"}]},{"type":"text","text":" (Go)."}]},{"type":"heading","attrs":{"level":2,"id":"examples"},"content":[{"type":"text","text":"Examples"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nums","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"target","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Result"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[4, 5, 6, 7, 0, 1, 2]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"0","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"4","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[4, 5, 6, 7, 0, 1, 2]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"3","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"-1","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[1, 2, 3, 4, 5]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"4","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"3","marks":[{"type":"code"}]},{"type":"text","text":" – no rotation"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[3, 1]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"7","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"-1","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"0 ≤ n ≤ 1,000,000","marks":[{"type":"code"}]},{"type":"text","text":", distinct values in the 32-bit "},{"type":"text","text":"int","marks":[{"type":"code"}]},{"type":"text","text":" range."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"O(log n)","marks":[{"type":"bold"}]},{"type":"text","text":" time, "},{"type":"text","text":"O(1)","marks":[{"type":"bold"}]},{"type":"text","text":" memory."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/search-in-rotated-sorted-array/","title":"LeetCode 33 – Search in Rotated Sorted Array","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:55.488Z","updatedAt":"2026-11-27T08:22:55.488Z"}