logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›binary search›logic building

Find out how many times the array is rotated

# Question

Given an array of integers nums of size nnn, sorted in ascending order with distinct values, which has been right-rotated between 000 and n−1n-1n−1 times. Determine the exact number of rotations performed.

# Solution

# Pattern

Binary Search for Minimum (Pivot Index) In a right-rotated sorted array, the number of rotations is mathematically identical to the index of the minimum element. Therefore, this problem is identical to "Find Minimum in Rotated Sorted Array". We use a left < right binary search comparing mid to the right boundary.

# How to Identify

  • The array is explicitly stated to be sorted and rotated.
  • You need to find a single structural anomaly (the pivot/minimum).
  • The required time complexity is O(log⁡n)O(\log n)O(logn).

# Description

Step-by-step explanation:

  1. A fully sorted array [1, 2, 3, 4, 5] rotated 2 times becomes [4, 5, 1, 2, 3]. The minimum element 1 is at index 2. The number of rotations is 2. The problem reduces to: Find the index of the minimum element.
  2. Initialize left = 0 and right = nums.size() - 1.
  3. Loop strictly while left < right to ensure the pointers converge on exactly one element.
  4. Calculate mid = left + (right - left) / 2.
  5. Evaluate nums[mid] &gt; nums[right]:
    • If TRUE: The sub-array from mid to right is unsorted. Because the original array was ascending, a larger number before a smaller number means the "wrap around" (the minimum) happened after mid. Discard the left half: left = mid + 1.
    • If FALSE: The sub-array from mid to right is perfectly sorted. Therefore, the minimum element in this entire section is mid. The absolute minimum of the array must be mid or somewhere to its left. Discard the right half: right = mid.
  6. When the loop terminates, left will equal right, pointing exactly at the minimum element.
  7. Return left (the index), which represents the number of rotations.

# The Intuition

Imagine an unrolled calendar for a week starting on Sunday: [Sun, Mon, Tue, Wed, Thu, Fri, Sat]. If you rotate it right by 3 days, you get [Thu, Fri, Sat, Sun, Mon, Tue, Wed]. If you want to know how many days it was rotated, you just need to find where "Sunday" (the original start/minimum) ended up. Sunday is at index 3. Therefore, it was rotated 3 times. To find Sunday quickly without checking every day, look at a day in the middle (e.g., Saturday). Compare it to the end of the array (Wednesday). Because Saturday comes after Wednesday in the week, you know the week must have "restarted" (Sunday) somewhere to your right.

# Complexity

LabelWorstAverage
Time ComplexityO(log⁡N)O(\log N)O(logN)O(log⁡N)O(\log N)O(logN)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

The search space is halved in every iteration based on a single O(1)O(1)O(1) comparison. For an array of size NNN, this requires at most log⁡2(N)\log_2(N)log2​(N) steps.

# Space Complexity

The algorithm uses only primitive pointers (left, right, mid), operating entirely in place. Auxiliary space is strictly O(1)O(1)O(1).

# Code

import java.util.List;
 
class Solution {
    public int findKRotation(List&lt;Integer&gt; nums) {
        if (nums == null || nums.isEmpty()) return 0;
 
        int left = 0;
        int right = nums.size() - 1;
 
        // Converge pointers to the minimum element
        while (left &lt; right) {
            int mid = left + (right - left) / 2;
 
            if (nums.get(mid) &gt; nums.get(right)) {
                // The minimum must be strictly to the right
                left = mid + 1;
            } else {
                // The right side is sorted, minimum is mid or to the left
                right = mid;
            }
        }
 
        // The index of the minimum element is the rotation count
        return left;
    }
}

# Caveats

  • Redundant left comparisons: Do not compare nums[left] to nums[mid]. It is a common mistake carried over from the "Search in Rotated Sorted Array" problem. Comparing left to mid fails to accurately determine the pivot when the array is fully sorted (0 rotations), because nums[left] &lt;= nums[mid] is true for both [1, 2, 3, 4, 5] and [4, 5, 1, 2, 3]. Comparing mid to right is universally foolproof.
  • Left vs Right Rotations: The problem specifies right rotations. If the problem specified left rotations, rotating [1, 2, 3, 4, 5] left by 2 yields [3, 4, 5, 1, 2]. The minimum 1 is at index 3. To find the number of left rotations, the formula changes to (n - min_index) % n.

# Concepts to Think About

  • Graphing the Array: Plotting the values of a rotated sorted array forms two distinct, parallel ascending lines. Finding the number of rotations is mathematically identical to finding the x-coordinate of the lowest point on the Y-axis.
  • Duplicates: The assumption of "distinct values" is critical. If duplicates are allowed, O(log⁡N)O(\log N)O(logN) is impossible in the worst case (e.g., [3, 3, 3, 1, 3]), and the algorithm degrades to O(N)O(N)O(N).
  • The Index-Rotation Identity: Why does the index of the minimum element equal the number of rotations? Think about the "0 rotations" case (index 0) vs. "1 rotation" (index 1).
  • The Right-Boundary Rule: Why is comparing to nums[right] safer than nums[left]? (Hint: In a non-rotated array, nums[left]<nums[mid] is true, but that doesn't tell you the pivot is on the right—there is no pivot!)
  • Termination: Why does left < right prevent an infinite loop when only two elements are left?

# Logical Follow-up

Question: How does the algorithm change if the array contains duplicate elements?

Solution: If there are duplicates, you can encounter a situation where nums[mid] == nums[right] (e.g., [10, 1, 10, 10, 10]). You can no longer guarantee which half contains the pivot. To handle this safely, you must add an else if (nums[mid] == nums[right]) block where you simply decrement right by 1 (right--). This slowly shrinks the window to resolve the duplicate ambiguity. In the worst case (an array of identical elements), this degrades the time complexity from O(log⁡N)O(\log N)O(logN) to O(N)O(N)O(N).

Question: "Now that you have the rotation count (kkk), how would you search for a specific target value in this same array in O(log⁡n)O(\log n)O(logn) time?"

Solution: You have two choices:

  1. The Two-Search Method: Use kkk to split the array into two sorted halves ([0...k-1] and [k...n-1]). Perform a standard binary search on the appropriate half.

  2. The "Virtual" Index Method: Perform one binary search on the whole array, but map the mid index to the "real" sorted index using:
    realMid=(mid+k)(modn)\text{realMid} = (\text{mid} + k) \pmod nrealMid=(mid+k)(modn)

Question (The Duplicate Trap): "Suppose the array contains duplicates (e.g., [2, 2, 2, 0, 2, 2, 2]). Does your O(log⁡n)O(\log n)O(logn) solution still work? If not, what is the new worst-case time complexity, and how do you handle it in a production environment at Google?"

Solution:

  1. The Problem: If nums[mid] == nums[right], you cannot tell if the pivot is to the left or right. The binary search "breaks."
  2. The Fix: When nums[mid]==nums[right]nums[mid] == nums[right]nums[mid]==nums[right], you must simply shrink the search space linearly by setting right = right - 1.
  3. Complexity: The worst-case time complexity becomes O(n)O(n)O(n) (e.g., an array of all 111s with one 000 hidden somewhere).
  4. Production Context: In an L5 role, you should mention that while the average case is still fast, we must be aware of O(n)O(n)O(n) "Degenerate Cases" for our Service Level Objectives (SLOs). We might even add telemetry to track how often our binary search "downgrades" to linear search.

Revised Loop Segment:

if (nums[mid] &gt; nums[right]) {
    left = mid + 1;
} else if (nums[mid] < nums[right]) {
    right = mid;
} else {
    // Ambiguity! Shrink the boundary linearly.
    right--;
}
PreviousFind Minimum in Rotated Sorted ArrayNextFind First and Last Position of Element in Sorted Array
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up