Secret Code Shuffler
JavaScript
easy
20 mins
You are given a string where each pair of characters represents a letter and a shift value.
- The first character in each pair is a lowercase letter.
- The second character is a digit (0-9) representing how many positions to shift the letter in the ASCII character set.
Function Signature
function decodeSecretCode(s) { // Your code here }
Parameters
s: A string where characters are paired as (letter, shift)
Return Value
- Return the decoded string by applying the shifts to each letter.
Example
Input: s = "a2b3c1" Output: "ced" Explanation: - "a2": 'a' (97) + 2 = 99 = 'c' - "b3": 'b' (98) + 3 = 101 = 'e' - "c1": 'c' (99) + 1 = 100 = 'd'
Input: s = "x1y2z3" Output: "y{}" Explanation: - "x1": 'x' (120) + 1 = 121 = 'y' - "y2": 'y' (121) + 2 = 123 = '{' - "z3": 'z' (122) + 3 = 125 = '}'
Input: s = "a0b0c0" Output: "abc" Explanation: Zero shifts leave letters unchanged
Rules
Character Pairs
- The string consists of pairs where:
- First character: lowercase letter (
a-z) - Second character: digit (
0-9) representing shift amount
- First character: lowercase letter (
Shift Calculation
- Add the shift value to the letter's ASCII code.
- No wrapping - characters can go beyond
'z'to{,}, etc. - Use
charCodeAt()andfromCharCode()for conversion.
Invalid Inputs
Return empty string for:
- Empty or null strings
- Strings with odd length (incomplete pairs)
- Strings with non-letter characters in odd positions
- Strings with non-digit characters in even positions
Constraints
0 ≤ s.length ≤ 1000- String length must be even (complete pairs)
- Only lowercase letters (
a-z) in odd positions - Only digits (
0-9) in even positions
Algorithm
- Check if input is valid (even length, proper character types).
- Process string in pairs of two characters.
- For each pair:
- Extract letter and shift value.
- Apply shift:
newCharCode = letter.charCodeAt(0) + shift - Convert back to character:
String.fromCharCode(newCharCode) - Add decoded character to result.
Test Cases
- Valid codes with various shift values
- Codes with characters beyond
'z'(e.g.,{,},|) - Zero shift values
- Invalid inputs (odd length, wrong character types)
- Empty string
- Edge cases with maximum shifts
Companies:
netflix
linkedin
adobe
spotify
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
