r/csinterviewproblems • u/parlezmoose • Dec 17 '15
[Strings] Write a function to build a string of length n
Write a function that takes as input a character "s" and an integer "n", and returns a string consisting of char "s" repeated n times. The function should be faster than O(n2 ).
Sample input: "a", 3
Sample output: "aaa"
5
Upvotes
2
u/parlezmoose Dec 17 '15
2
u/rcheu Dec 18 '15
This is literally not possible, who asked you this? At some point you need to write a string that is n characters and store that in memory which will take O(n). I'm a bit dismayed at the answers here suggesting that you can do this faster. The only way that's possible is if you change your representation of a string.
Perhaps people who didn't start learning with C don't have a good grasp of how long things will take.
1
u/WarDEagle Dec 22 '15 edited Dec 22 '15
Java I believe it's O(2n), but someone correct me if new String() is not O(n):
EDIT: Formatting
1
u/manwith4names Dec 18 '15
Python 3
Is there a way to do it faster than that?
1
u/YesIAmTheMorpheus Dec 18 '15 edited Dec 18 '15
This can basically be done by changing n multiplications to log n multiplications.
C++
-1
u/missblit Dec 18 '15
Am I doing it right?