← All Lessons Lesson 24 / 68
Lesson 24

Reverse Segments: Flipping the First k Characters of Every 2k Block

Reverse Segments

This is a string puzzle. You are given a piece of text called s and a number called k. Your job is to walk through the text in fixed-size chunks and flip certain parts of each chunk around.

What the rule actually says

Imagine you cut the string into pieces, where each piece is 2k characters long. So if k = 2, then 2k = 4, and each piece holds 4 characters.

For every piece, you do one simple thing: reverse only the first k characters of that piece. The rest of the piece stays exactly as it is.

"Reverse" just means read those characters backwards. For example, reversing abcd gives dcba.

The edge cases at the end

The string might not divide neatly into pieces of 2k. The last piece can be short. Two simple rules handle this:

  1. If fewer than k characters are left, reverse all of them. (You can't reverse k characters if there aren't even k there, so just flip whatever remains.)
  2. If at least k but fewer than 2k characters are left, reverse only the first k, and leave the rest alone — the same as a full piece.

You can think of both rules together as one idea: *always try to reverse k characters from the start of the chunk; if there aren't that many, reverse all you have.*

Walking through the example

Let's use s = abcdefghij and k = 2, so 2k = 4.

Split the string into pieces of 4:

  • Piece 1: abcd
  • Piece 2: efgh
  • Piece 3: ij (only 2 characters left)

Now reverse the first k = 2 characters of each piece:

  • abcd → reverse abba, keep cdbacd
  • efgh → reverse effe, keep ghfegh
  • ij → only 2 characters left, which is fewer than 2k but at least k, so reverse the first 2 → ji

Glue the pieces back together: bacd + fegh + ji = bacdfeghji.

That matches the expected output.

How to think about the code

A clean way to solve this is to jump through the string in steps of 2k. At each jump:

  • You are standing at some position i (the start of a piece): i = 0, then i = 4, then i = 8, and so on.
  • Figure out how many characters you can safely reverse: it is k, unless fewer than k remain, in which case it is "all the rest."
  • Reverse just that little stretch, then move on.

In C++, the function lives inside the given class:

string reverseSegments(string s, int k) {
}

Inside it, you loop with i increasing by 2k each time. At each i, reverse the characters from index i up to i + k (but never past the end of the string), then continue. When the loop finishes, return s.

The trick that makes this easy is the jump of 2k: by stepping that far each time, the characters between the reversed parts are skipped automatically, so you never touch them. You only ever flip the first k of each block.

Reverse Segments: Flipping the First k Characters of Every 2k Block
Diagram — click to zoom (scroll / drag to pan)