Reverse String II

EasyTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a string s and an integer k, split s into consecutive blocks of 2k characters (the final block may be shorter). In every block, reverse the **first k** characters and leave the rest unchanged. For the last block: if it has fewer than k characters, reverse all of them; if it has at least k but fewer than 2k, reverse just the first k. Return the resulting string.

Examples

Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Blocks are "abcd" and "efg"; reversing the first 2 of each gives "bacd" and "feg".
Input: s = "abcd", k = 4
Output: "dcba"
One block of 4 characters, all of which are in the first k.

Constraints

  • 1 <= s.length <= 10^4
  • `s` consists of lowercase English letters
  • 1 <= k <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems