Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

880. Decoded String at Index

StringStack

Explanation:

To solve this problem, we need to simulate the decoding process and keep track of the length of the decoded string in order to determine the kth letter. We can iterate through the encoded string character by character, updating the length of the decoded string according to the rules provided. When the length of the decoded string exceeds k, we can backtrack to find the exact kth letter.

  1. Iterate through the encoded string character by character.
  2. If the character is a digit, update the length of the decoded string by multiplying it with the digit value.
  3. If the character is a letter, increment the length of the decoded string by 1.
  4. Keep track of the kth letter by decrementing k whenever the length of the decoded string becomes larger than k.
  5. When the length of the decoded string equals or surpasses k, backtrack through the encoded string to find the kth letter.

Time Complexity: O(n), where n is the length of the encoded string. Space Complexity: O(1)

:

class Solution {
    public String decodeAtIndex(String s, int k) {
        long size = 0;
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                size *= (c - '0');
            } else {
                size++;
            }
        }
        
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            k %= size;
            if (k == 0 && Character.isLetter(c)) {
                return Character.toString(c);
            }
            
            if (Character.isDigit(c)) {
                size /= (c - '0');
            } else {
                size--;
            }
        }
        
        throw new IllegalArgumentException("Invalid input");
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.