All problems
0308EasyTwo PointersString

Alternating Block Flip

Tracked in this browser only
Write code

Trains the technique from

LeetCode 541Reverse String II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A ribbon printer receives a strip of lowercase letters, strip, and a block size, block.

Reading from the left, cut the strip into consecutive blocks of block letters each. The last block is whatever is left over, so it may hold fewer than block letters. Number the blocks 1, 2, 3, ... from the left.

The printer flips every odd-numbered block, that is blocks 1, 3, 5, ..., reversing the order of the letters inside that block only. Even-numbered blocks come out untouched. A short final block is flipped just the same if its number is odd.

Return the strip the printer produces.

Examples

Example 1

Input
strip = "photograph", block = 3
Output
"ohptogparh"

The blocks are "pho", "tog", "rap" and "h". Flipping blocks 1 and 3 gives "ohp", "tog", "par" and "h", which join into "ohptogparh".

Example 2

Input
strip = "carousel", block = 3
Output
"racousle"

The blocks are "car", "ous" and "el". Block 3 holds only two letters and is still flipped, so the pieces become "rac", "ous" and "le".

Example 3

Input
strip = "windmill", block = 5
Output
"mdniwill"

The blocks are "windm" and "ill". Block 1 flips to "mdniw" and block 2 is left alone.

Example 4

Input
strip = "kite", block = 9
Output
"etik"

The block size is larger than the strip, so the whole strip is block 1 and the entire thing is flipped.

Example 5

Input
strip = "lantern", block = 1
Output
"lantern"

Every block holds a single letter, and flipping one letter changes nothing.

Constraints

  • 1 <= strip.length <= 10^4
  • strip consists of only lowercase English letters.
  • 1 <= block <= 10^4

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def flip_blocks(strip: str, block: int) -> str:
Java
public String flipBlocks(String strip, int block)
September 7
Apply