Solution 1: Time limit exceeded
Time: O(n^2), Space: O(n)
The look-backs lead to maximum O(n^2) time complexity.
Solution 2: Accepted
Time: O(n), Space: O(n)
Store the previous result rather than looking back.
Interesting: change from String to StringBuilder does not bring any performance boost.
Using String
Using StringBuilder
Solution 3: Accepted
Improved solution 1 without looking back.
Solution 4: Accepted
Improved solution 3, replacing hashmap with array. Even faster.
Test case 1
Solution 1: ~70ms
Solution 2: ~20ms
Solution 3: ~10ms
Solution 4: ~4ms
|
|