Efficient O(n) Solution with Explanation
Explanation\n Describe your approach to solving the problem. \nInitialization:\n\nThe input string is s = "cbabd".\nn is the length of the string, so n = 5.\ni 
# Explanation\n<!-- Describe your approach to solving the problem. -->\nInitialization:\n\nThe input string is s = "cbabd".\nn is the length of the string, so n = 5.\ni is initialized to 0.\n\n\n**First Loop:**\n\nwhile(i < n && s[i] == \'a\') {\n    i++;\n}\nThis loop increments i as long as s[i] is \'a\'. In the given string, none of the characters are \'a\' at the start. Therefore, this loop does not run, and i remains 0.\n\n**Check if All Characters Are \'a\':**\n\nif(i == n) {\n    s[n - 1] = \'z\';\n    return s;\n}\n\n\nAfter the first loop, i is 0 and not equal to n (which is 5). Hence, the condition i == n is false.\nThis means we skip this block of code and do not modify the last character to \'z\'.\n\n\n **second loop**\n\nwhile(i < n && s[i] != \'a\') {\n    s[i]--;\n    i++;\n}\nThis loop decrements s[i] by 1 as long as s[i] is not \'a\' and i is within bounds.\nLet\'s go through this loop step by step\n\nand when get a  then return s;\n\n# Complexity\n- Time complexity:\n- O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n    string smallestString(string s) {\n       int n=s.size(), i=0;\n       \n        while(i<n && s[i]==\'a\'){\n             i++;\n        }\n        if(i==n){\n            s[n-1]=\'z\';\n            return s;\n        }\n        while(i<n && s[i]!=\'a\'){\n            s[i]--;\n            i++;\n        }\n        \n        return s;\n\n\n    }\n};\n```
['C++']