From d0182261d9172aca303a44aa735e0a291e4d9499 Mon Sep 17 00:00:00 2001 From: Aditya Bhuran Date: Sun, 7 Jun 2026 23:13:07 -0400 Subject: [PATCH] Rotational sort and unknown range --- problem2.py | 29 +++++++++++++++++++++++++++++ problem3.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 problem2.py create mode 100644 problem3.py diff --git a/problem2.py b/problem2.py new file mode 100644 index 00000000..3f0bec9c --- /dev/null +++ b/problem2.py @@ -0,0 +1,29 @@ +# Time Complexity : O(log n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : yes +# Any problem you faced while coding this : No + +class Solution(object): + def search(self, nums, target): + low = 0 + high = len(nums) - 1 + + while low <= high: + mid = low + (high - low) // 2 + #left sorted + if nums[mid] == target: + return mid + #left sorted + if nums[low] <= nums[mid]: + if nums[low] <= target < nums[mid]: + high = mid - 1 + else: + low = mid + 1 + else: #right sorted + if nums[mid] < target <= nums[high]: + low = mid + 1 + else: + high = mid - 1 + return -1 + + \ No newline at end of file diff --git a/problem3.py b/problem3.py new file mode 100644 index 00000000..13e57119 --- /dev/null +++ b/problem3.py @@ -0,0 +1,30 @@ +# Time Complexity : O(log m + log n) +# Space Complexity : O(1) +# Did this code successfully run on Leetcode : yes +# Any problem you faced while coding this : No, it was a bit tricky to understand the problem statement and how to approach it, but once I got the idea, it was straightforward. + + + +def search(self, reader: 'ArrayReader', target: int) -> int: + #this is to understand the range of the array, we will keep doubling the high until we find a value that is greater than the target + low = 0 + high = 1 + while reader.get(high) < target: + low = high + high = high * 2 + #after this we will implement binary search on the range we found + while low <= high: + mid = low + (high - low) // 2 + if reader.get(mid) == target: + return mid + if reader.get(low) <= reader.get(mid): + if reader.get(low) <= target < reader.get(mid): + high = mid - 1 + else: + low = mid + 1 + else: + if reader.get(mid) < target <= reader.get(high): + low = mid + 1 + else: + high = mid - 1 + return -1