Advertisement
Guest User

Smallest Lexicographical Rotation

a guest
Apr 24th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const assert = require('assert');
  2.  
  3. /**
  4.  * Finds the number of rotations required to find the
  5.  * smallest lexicographically ordered rotation
  6.  * Runtime: O(N)
  7.  * Space: 0(1)
  8.  * @param {string} s
  9.  */
  10. const findMinimumRotations = (s) => {
  11.     const concat = s + s;
  12.     const failure = s.split('').map(c => -1);
  13.     let rotations = 0;
  14.     for (let i = 1; i < concat.length; i++) {
  15.         const prefix = concat[i];
  16.         let failureLookup = failure[i - rotations - 1];
  17.         while (failureLookup != -1 && prefix != concat[rotations + failureLookup + 1]) {
  18.             if (prefix < concat[rotations + failureLookup + 1]) {
  19.                 rotations = i - failureLookup - 1;
  20.             }
  21.             failureLookup = failure[failureLookup];
  22.         }
  23.         if (prefix != concat[rotations + failureLookup + 1]) {
  24.             if (prefix < concat[rotations]) {
  25.                 rotations = i;
  26.             }
  27.             failure[i - rotations] = -1;
  28.         } else {
  29.             failure[i - rotations] = failureLookup + 1;
  30.         }
  31.     }
  32.     return {
  33.         rotations,
  34.         word: s.substring(rotations) + s.substring(0, rotations)
  35.     };
  36. }
  37.  
  38. it('should find rotations', () => {
  39.     assert.deepEqual(findMinimumRotations('bebaafc'), { rotations: 3, word: 'aafcbeb' });
  40.     assert.deepEqual(findMinimumRotations('bcdefbcdea'), { rotations: 9, word: 'abcdefbcde' });
  41.     assert.deepEqual(findMinimumRotations('acabaaabaa'), { rotations: 4, word: 'aaabaaacab' });
  42.     assert.deepEqual(findMinimumRotations('cfgechge'), { rotations: 0, word: 'cfgechge' });
  43. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement