Sunday, October 12, 2025
HomeData Modelling & AICheck if given Morse Code is valid

Check if given Morse Code is valid

Given a string S representing a Morse Code, the task is to check is the code is valid or not. A Morse code is valid if that meets all the below requirements:

  • Any message must begin with a dot. [ ‘.’ ]
  • Any message must end with a dash. [ ‘-‘ ]
  • Every dot must have a corresponding dash after it to close it.

Examples:

Input: S = “.–“
Output: Valid

Input: S = “.”
Output: Invalid

Input: S = “-“
Output: Invalid

 

Approach: This is a simple implementation based problem where the first, last and each pair of characters need to be checked for the given conditions. Follow the given steps to solve the problem:

  • If the first or last characters are not dot and dash respectively then the string is invalid.
  • Traverse the message from 0 to N-1:
    • If the character at index i is a dot but at index i+1 is not a dash (-), then the code is invalid.
  • If the loop ends, means the message has met all the requirements. So the code is valid.

Below is the implementation for the above approach:

C++14




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find if
// the Morse code is valid or not
bool isValidMorse(string& code)
{
    int n = code.length();
 
    if (code[0] != '.' || code[n - 1] != '-')
        return 0;
 
    for (int i = 0; i < n - 1; i++) {
        if (code[i] == '.' && code[i + 1] != '-')
            return 0;
    }
 
    return 1;
}
 
// Driver's code
int main()
{
    string code = ".--";
 
    // Function Call
    if (isValidMorse(code))
        cout << "Valid";
    else
        cout << "Invalid";
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
  // Java code to implement the approach
 
  // Function to find if
  // the Morse code is valid or not
  static boolean isValidMorse(String code)
  {
    int n = code.length();
 
    if (code.charAt(0) != '.' || code.charAt(n - 1) != '-')
      return false;
 
    for (int i = 0; i < n - 1; i++) {
      if (code.charAt(i) == '.' && code.charAt(i + 1) != '-')
        return false;
    }
 
    return true;
  }
 
 
  /* Driver program to test above function*/
  public static void main(String args[])
  {
    String code = ".--";
 
    // Function Call
    if (isValidMorse(code))
      System.out.println("Valid");
    else
      System.out.println("Invalid");
  }
}
 
// This code is contributed by shinjanpatra.


Python3




# Python3 code to implement the approach
 
# Function to find if
# the Morse code is valid or not
def isValidMorse(code):
 
    n = len(code)
 
    if (code[0] != '.' or code[n - 1] != '-'):
        return 0
 
    for i in range(n-1):
        if (code[i] == '.' and code[i + 1] != '-'):
            return 0
 
    return 1
 
# Driver's code
 
code = ".--"
 
# Function Call
if (isValidMorse(code)):
    print("Valid")
else:
    print("Invalid")
 
# This code is contributed by shinjanpatra


C#




/*package whatever //do not write package name here */
using System;
 
public class GFG
{
 
  // C# code to implement the approach
 
  // Function to find if
  // the Morse code is valid or not
  static bool isValidMorse(String code)
  {
    int n = code.Length;
 
    if (code[0] != '.' || code[(n - 1)] != '-')
      return false;
 
    for (int i = 0; i < n - 1; i++) {
      if (code[i] == '.' && code[(i + 1)] != '-')
        return false;
    }
 
    return true;
  }
 
 
  /* Driver program to test above function*/
  public static void Main(String []args)
  {
    String code = ".--";
 
    // Function Call
    if (isValidMorse(code))
      Console.WriteLine("Valid");
    else
      Console.WriteLine("Invalid");
  }
}
 
// This code contributed by shikhasingrajput


Javascript




<script>
       // JavaScript code for the above approach
 
 
       // Function to find if
       // the Morse code is valid or not
       function isValidMorse(code) {
           let n = code.length;
 
           if (code[0] != '.' || code[n - 1] != '-')
               return 0;
 
           for (let i = 0; i < n - 1; i++) {
               if (code[i] == '.' && code[i + 1] != '-')
                   return 0;
           }
 
           return 1;
       }
 
       // Driver's code
 
       let code = ".--";
 
       // Function Call
       if (isValidMorse(code))
           document.write("Valid");
       else
           document.write("Invalid");
 
   // This code is contributed by Potta Lokesh
   </script>


Output

Valid

Time Complexity: O(N)
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32352 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6720 POSTS0 COMMENTS
Nicole Veronica
11885 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6840 POSTS0 COMMENTS
Ted Musemwa
7105 POSTS0 COMMENTS
Thapelo Manthata
6796 POSTS0 COMMENTS
Umr Jansen
6795 POSTS0 COMMENTS