-2

I want to reverse a string without using any additional memory (O(1) space complexity) in O(N) time complexity, where N is the length of the string.

I can’t use the string reverse in built function.

kdbanman
  • 10,161
  • 10
  • 46
  • 78
akira
  • 521
  • 2
  • 5
  • 14
  • 3
    You can't. The question requires that the string be reversed in place, which isn't possible in Python because strings are immutable. The slicing suggestion above creates a new string, which requires additional memory. – kindall Oct 21 '15 at 21:16
  • 1
    Possible duplicate of [Reverse a string in Python](http://stackoverflow.com/questions/931092/reverse-a-string-in-python) – MattDMo Oct 21 '15 at 21:17
  • 1
    @MattDMo, that doubles memory consumption from the original string. – kdbanman Oct 21 '15 at 21:17
  • 2
    _Why_? Why can't you use more memory? Not even 1 byte? _Why_ can't you use the built-in reverse functions? – Two-Bit Alchemist Oct 21 '15 at 21:17
  • 1
    @Two-BitAlchemist, probably because it's a homework question that either A) gets the student to realize that python strings are immutable, or B) doesn't actually require python usage, or C) is written by someone who doesn't know python. – kdbanman Oct 21 '15 at 21:18
  • 2
    @kdbanman This is why I wish we had a close reason for something like: "Your question appears to have absurd or contradictory requirements and offers no explanation why." I really dislike when it seems like a game because there's nonsense parameters that are not obvious from the question itself. – Two-Bit Alchemist Oct 21 '15 at 21:19

1 Answers1

5

You can't do this. Whoever is asking you to do this is

  1. trying to get you to realize that python strings are immutable, or
  2. doesn't actually require you to use python, or
  3. doesn't know python at all.

Python strings are immutable, which means they cannot be changed in-place.

kdbanman
  • 10,161
  • 10
  • 46
  • 78