Skip to content

Latest commit

 

History

History
22 lines (17 loc) · 973 Bytes

Better_Solution.md

File metadata and controls

22 lines (17 loc) · 973 Bytes

Code generated by Bard

We can optimize the space complexity of the vector v. Instead of storing entire strings, we can only store the characters at their corresponding indices. This would require O(n) space for the vector and the final output string, resulting in a total space complexity of O(n).

Here's how the code could be modified for optimized space:

class Solution {
public:
    string restoreString(string s, vector<int>& indices) {
        string output(s.size(), ' ');
        for (int i = 0; i < indices.size(); ++i) {
            output[indices[i]] = s[i];
        }
        return output;
    }
};

This version iterates through the string just once and directly assigns characters to their correct positions in the output string, maintaining only one string in memory at a time.

Therefore, in summary, the space complexity of the original code can be reduced to O(n) with a slight modification, making it both time and space efficient.