Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

In-Place String Reversal

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is In-Place String Reversal. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Implement two in-place operations without using additional memory allocation: reverse a string represented as a mutable character array, and swap two integers without using a temporary variable.

Write a function that performs one of the following based on the input mode:

  1. mode == "reverse": reverse the list of single-character strings in place.
  2. mode == "swap": swap two integers and return the swapped pair.

Formal Specification

  • Input:
    • mode, a string equal to "reverse" or "swap"
    • If mode == "reverse", data is a list of single-character strings
    • If mode == "swap", data is a list of exactly two integers
  • Output:
    • If mode == "reverse", return the modified character list
    • If mode == "swap", return the swapped two-element list
  • Do not use extra arrays, strings, or other auxiliary storage proportional to input size.

Constraints

  • 1 <= len(data) <= 10^5
  • For reverse, data contains single-character strings
  • For swap, len(data) == 2
  • Use O(1) extra space
  • No additional arrays or strings proportional to input size

Function Signature

def in_place_reverse_or_swap(mode, data):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output