Morse Code Translator - Problem

Build a bidirectional Morse code translator that can both encode text to Morse code and decode Morse code back to text.

Your translator should:

  • Encode: Convert alphabetic characters (A-Z, case insensitive) to Morse code
  • Decode: Convert Morse code back to uppercase letters
  • Handle spaces: Single space between Morse letters, double space between words
  • Ignore: Non-alphabetic characters during encoding

Use the standard International Morse Code mapping where A = '.-', B = '-...', etc.

Input & Output

Example 1 — Encoding Text to Morse
$ Input: text = "HELLO WORLD", mode = "encode"
Output: .... . .-.. .-.. --- .-- --- .-. .-.. -..
💡 Note: Each letter is converted to its Morse code: H=...., E=., L=.-.., L=.-.., O=---. Single spaces separate letters, double spaces separate words.
Example 2 — Decoding Morse to Text
$ Input: text = ".... . .-.. .--.", mode = "decode"
Output: HELP
💡 Note: Each Morse pattern is converted back: ....=H, .=E, .-..=L, .--.=P
Example 3 — Multiple Words
$ Input: text = "... --- ... -- --- .-. ... .", mode = "decode"
Output: SOS MORSE
💡 Note: Double spaces indicate word boundaries. First word: S=..., O=---, S=... gives 'SOS'. Second word gives 'MORSE'.

Constraints

  • 1 ≤ text.length ≤ 1000
  • text contains only letters, spaces, dots, and dashes
  • mode is either "encode" or "decode"

Visualization

Tap to expand
INPUTALGORITHMRESULTHELLOText InputencodeModeLetter → Morse MapH → ....E → .L → .-..O → ---1Build Hash MapsCreate letter→morse andmorse→letter mappings2Process Each CharacterFor each letter in input,lookup morse code in O(1)3Handle SpacingSingle space between letters,double space between words.... . .-.. .-.. ---Morse Code OutputTranslationH → ....E → .L → .-.., L → .-..O → ---Key Insight:Hash maps provide instant O(1) bidirectional translation - no linear searching through alphabet arrays needed!TutorialsPoint - Morse Code Translator | Hash Map Approach
Asked in
Meta 15 Microsoft 12 Amazon 8
25.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen