Interview 150
Rotate Array
- Problem
- LC 189
- File
- interview150_LC189RotateArray.java
- Path
- pkg5leetcode/interview150/interview150_LC189RotateArray.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC189RotateArray.java
- Approach
- Reverse whole array then reverse first k and rest.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.interview150;2 3/*4 * Rotate Array | LC 1895 * APPROACH: Reverse whole array then reverse first k and rest.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC189RotateArray {9 static void rotate(int[] nums, int k) {10 k %= nums.length;11 reverse(nums, 0, nums.length - 1);12 reverse(nums, 0, k - 1);13 reverse(nums, k, nums.length - 1);14 }15 16 static void reverse(int[] a, int lo, int hi) {17 while (lo < hi) { int t = a[lo]; a[lo++] = a[hi]; a[hi--] = t; }18 }19 20 public static void main(String[] args) {21 int[] a = {1, 2, 3, 4, 5, 6, 7};22 rotate(a, 3);23 check(java.util.Arrays.equals(a, new int[]{5, 6, 7, 1, 2, 3, 4}), "case1");24 int[] b = {-1};25 rotate(b, 2);26 check(java.util.Arrays.equals(b, new int[]{-1}), "case2");27 System.out.println("all tests passed");28 }29 30 static void check(boolean cond, String name) {31 if (!cond) throw new AssertionError("FAILED: " + name);32 System.out.println(" PASS " + name);33 }34}