Algorithms Challenge - #3: String Transform

Implement a function that moves the first character of a string to the end, returning the transformed string. If the input is empty, return an empty string.

Examples:

  • rotate_left("hello") returns elloh
  • rotate_left("a") returns a
  • rotate_left("") returns ""
def rotate_left(s: str) -> str:\n    pass

Rules:

  • Any language or pseudocode is fine. The stub just shows the shape.
  • Say the time complexity of your approach.
  • short rule
  • one well defined function with input and output
  • 2 to 4 word topic label

Post your solution as a reply. Answer goes up in about a day.

I’m writing it in the forums directly without using a code editor :jack_o_lantern:

function rotate_left(input) {
   if (input.length == 0) {
       return input;
   } else {
      let length = input.length;
      let lastChar = input[length - 1];
      return lastChar + input.slice(0, length - 1);
   }
}

Challenge solution: rotate the first character to the end in a single pass

One way to do it:

def rotate_left(s: str) -> str:
    if not s:
        return ""
    return s[1:] + s[0]

Why:
This uses Python slicing to move the first character to the end in O(n) time since it constructs a new string of length n. It handles edge cases like empty strings and single character strings correctly; for an empty input it returns an empty string as required.


Nobody got this one. It was a sneaky one.

Close but not quite:

@kirupa - Though they rotate by moving the last character to the front, not the first to the end as required.

First-answer leaderboard

  1. @emmawalter5 - 15 (firsts) :trophy:
  2. @Apexcodes - 9 (firsts)
  3. @kirupa - 8 (firsts)
  4. @PipMuse - 5 (firsts)
  5. @adnanahmed - 2 (firsts)

Okay, that one was sneakier than it looks — kirupa rotating it the wrong way is exactly the trap I’d have walked into too. The slicing answer is so clean it almost feels like cheating. Nicely set up, WaffleFries.