More formally, let str be the string in question, and let its length be l. I am aware that the above can easily be accomplished using the substr function as follows:
- Removing the first character –
str.substr(1) - Removing the last character –
str.substr(0,l-1)
But according to this page, the above method does so in O(l).
Is there a way to achieve the same in O(1)?
Edit: Before you mark this question as a duplicate, note that I am asking for an O(1) implementation for removing the terminal characters of a string. None of the answers to question of which this one is seemingly a duplicate of make any effort to answer this, apparently because that question doesn’t ask for it.
The
substrfunction doesn’t remove characters. The string you call that function on does not get modified, so all characters remain intact. Nonetheless, the time required to call it to select a substring that includes all but a terminal character will be O(n) because it involves making a copy of all the other characters.The time required for removing a character from a string lies in shifting all the subsequent characters to replace the one removed, much like the copying that occurs in
substr. There are in general n characters in a string, so the complexity of removing an arbitrary character is O(n).There is no constant-time way to remove the first character of a string of arbitrary length. Removing a character that’s a fixed number of characters C from the end of a string can be done in constant time, so removing the final character (C = 0) is O(1).
If you frequently need to add or remove elements from the termini of a sequence, you might consider a data structure more suited to that operation. Both
listanddequeare good for that.