Skip to content

1806. Minimum Number of Operations to Reinitialize a Permutation

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int reinitializePermutation(int n) {
    int ans = 0;
    int i = 1;

    do {
      if (i < n / 2)
        i = i * 2;
      else
        i = (i - n / 2) * 2 + 1;
      ++ans;
    } while (i != 1);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int reinitializePermutation(int n) {
    int ans = 0;
    int i = 1;

    do {
      if (i < n / 2)
        i = i * 2;
      else
        i = (i - n / 2) * 2 + 1;
      ++ans;
    } while (i != 1);

    return ans;
  }
}