- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 65 lines of Java from the credited upstream file 1850.java.
- The implementation visibly relies on sequence storage.
- 8 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int getMinSwaps(String num, int k) {3 int[] original = new int[num.length()];4 5 for (int i = 0; i < original.length; ++i)6 original[i] = num.charAt(i) - '0';7 8 int[] permutated = original.clone();9 10 for (int i = 0; i < k; ++i)11 nextPermutation(permutated);12 13 return countSteps(original, permutated);14 }15 16 public void nextPermutation(int[] nums) {17 final int n = nums.length;18 19 20 int i;21 for (i = n - 2; i >= 0; --i)22 if (nums[i] < nums[i + 1])23 break;24 25 26 if (i >= 0)27 for (int j = n - 1; j > i; --j)28 if (nums[j] > nums[i]) {29 swap(nums, i, j);30 break;31 }32 33 34 reverse(nums, i + 1, n - 1);35 }36 37 private void reverse(int[] nums, int l, int r) {38 while (l < r)39 swap(nums, l++, r--);40 }41 42 private void swap(int[] nums, int i, int j) {43 final int temp = nums[i];44 nums[i] = nums[j];45 nums[j] = temp;46 }47 48 private int countSteps(int[] A, int[] B) {49 int count = 0;50 51 for (int i = 0, j = 0; i < A.length; ++i) {52 j = i;53 while (A[i] != B[j])54 ++j;55 while (i < j) {56 swap(B, j, j - 1);57 --j;58 ++count;59 }60 }61 62 return count;63 }64}65