Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Check if Given String can be Split into Four Distinct Strings
Next article icon

JavaScript Program to Check if Given String can be Split into Four Distinct Strings

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A string can be split into four distinct strings by identifying specific delimiters or patterns within the original string and extracting substrings based on these divisions, resulting in four separate and non-overlapping text segments. In this article, we will check if a given string can be split into four distinct strings.

Table of Content

  • Using Regular Expression
  • Using Recursive Method
  • Using The Length Property
  • Using Sorting
  • Using Substring Method and Set
  • Using the Map Data Structure

Using Regular Expression

In this approach, Regular Expression, or regex, is a pattern-matching technique used in programming to search, match, and manipulate text based on specific patterns or rules, enabling versatile text processing and validation.

It first checks if the string's length is divisible by 4. If so, it uses regex to split the string into segments and checks if there are four unique segments.

Syntax:

const regex = new RegExp(`.{${inputString.length / 4}}`, 'g');

Example: In this example we are using above mentioned approach.

JavaScript
const inputStr1 = "GeeksforGeeks"; const inputStr2 = "abcdefgh";  const checkSplittable = (inputString) => {     return inputString.length % 4 !== 0         ? false         : (() => {             const regex =                     new RegExp(                         `.{${inputString.length / 4}}`, 'g');             const segments =                      inputString.match(regex);             return segments && new Set(segments).size === 4;         })(); };  console.log(`     "${inputStr1}" is splittable:      ${checkSplittable(inputStr1)}`); console.log(`     "${inputStr2}" is splittable:      ${checkSplittable(inputStr2)}`); 

Output
    "GeeksforGeeks" is splittable:      false      "abcdefgh" is splittable:      true 

Using Recursive Method

Here we are using recursive approach to determine if a given string can be split into four distinct substrings. It checks if a substring can be split further and maintains distinctness, returning "Yes" if possible, "No" otherwise.

Example: In this example we are using above mentioned approach.

JavaScript
function isDistinct(s1, s2) {     return s1.localeCompare(s2) !== 0; } function distinctStrings(s) {     if (s.length < 4) {         return false;     }     function splitAndCheck(s, val) {         if (val === 0) {             return true;         }         for (let i = 1; i < s.length; i++) {             const s1 = s.substring(0, i);             const s2 = s.substring(i);              if (isDistinct(s1, s2)) {                 if (splitAndCheck(s2, val - 1)) {                     return true;                 }             }         }         return false;     }     return splitAndCheck(s, 4); }  const inputStr = "GeeksforGeeks"; if (distinctStrings(inputStr)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes 

Using The Length Property

In this approach, we are using the length property to divide input strings into four equal segments. It checks if the length is divisible by 4 and creates substrings. It ensures each substring's uniqueness and equal length, determining if the input can be split into four distinct strings.

Example: In this example, we check if a given string can be split into four equal-length, distinct substrings. It verifies divisibility by 4, creates substrings, and ensures uniqueness.

JavaScript
let str1 = "GeeksforGeeks"; let str2 = "GeeksforGeeksExample";  function isDistinct(str) {     if (str.length % 4 !== 0) {         return false;     }      let length = str.length / 4;     let substrings = {};      let i = 0;     for (const char of str) {         if (i % length === 0) {             let substring = str.substring(i, i + length);             if (substrings[substring] ||                  substring.length !== length) {                 return false;             }             substrings[substring] = true;         }         i++;     }      return Object.keys(substrings).length === 4; }  console.log(`String: "${str1}"`); if (isDistinct(str1)) {     console.log(`result: The string can be                  split into four distinct strings.`); } else {     console.log(`result: The string cannot be          split into four distinct strings.`); }  console.log(`\nString: "${str2}"`); if (isDistinct(str2)) {     console.log(`result: The string can be          split into four distinct strings.`); } else {     console.log(`result: The string cannot          be split into four distinct strings.`); }; 

Output
String: "GeeksforGeeks" result: The string cannot be          split into four distinct strings.  String: "GeeksforGeeksExample" result: The string can be          split into four distinct strings. 

Using Sorting

Using sorting, the approach generates all possible combinations of four substrings, sorts them, and checks if adjacent substrings are distinct. If all adjacent substrings are distinct, the string can be split into four distinct strings.

Example:

JavaScript
function canSplitIntoFourDistinctStrings(str) {     let substrings = [];     let n = str.length;     for (let i = 1; i < n; i++) {         for (let j = i + 1; j < n; j++) {             for (let k = j + 1; k < n; k++) {                 let first = str.slice(0, i);                 let second = str.slice(i, j);                 let third = str.slice(j, k);                 let fourth = str.slice(k);                 substrings = [first, second, third, fourth];                 substrings.sort();                 if (substrings[0] !== substrings[1] && substrings[1] !== substrings[2]                  && substrings[2] !== substrings[3]) {                     return true;                 }             }         }     }     return false; }  console.log(canSplitIntoFourDistinctStrings("abcdefgh")); // true console.log(canSplitIntoFourDistinctStrings("abcdabcdabcdabcd")); // false 

Output
true true 

Using Substring Method and Set

In this approach, we utilize the substring method to divide the string into four equal segments. We then store these segments in a set data structure, which automatically removes duplicate entries. By checking the size of the set, we can determine if the string can be split into four distinct substrings.

Example:

JavaScript
function canSplitIntoFourDistinctStrings(str) {     if (str.length % 4 !== 0) {         return false; // If the length is not divisible by 4, it cannot be split into four equal segments     }          const segmentLength = str.length / 4;     const segments = new Set(); // Using Set to store unique segments          for (let i = 0; i < str.length; i += segmentLength) {         const segment = str.substring(i, i + segmentLength);         segments.add(segment);     }          return segments.size === 4; // If there are four unique segments, return true }  console.log(canSplitIntoFourDistinctStrings("abcdefgh"));  console.log(canSplitIntoFourDistinctStrings("abcdabcdabcdabcd")); 

Output
true false 

Using the Map Data Structure

In this approach, we use the Map data structure to store the frequency of each substring. The string is first divided into four segments, and then we check if each segment is unique by ensuring the frequency of each substring in the Map is one.

Example: In this example, we demonstrate how to use the Map data structure to check if a given string can be split into four distinct substrings.

JavaScript
const canBeSplitIntoFourDistinctStrings = (inputString) => {     if (inputString.length % 4 !== 0) {         return "No";     }      const segmentLength = inputString.length / 4;     const segments = [];     const map = new Map();      for (let i = 0; i < 4; i++) {         const segment = inputString.substring(i * segmentLength, (i + 1) * segmentLength);         segments.push(segment);         map.set(segment, (map.get(segment) || 0) + 1);     }      for (let value of map.values()) {         if (value > 1) {             return "No";         }     }      return "Yes"; };  console.log(canBeSplitIntoFourDistinctStrings("abcdabcdabcdabcd"));  console.log(canBeSplitIntoFourDistinctStrings("abcd1234efgh5678"));  console.log(canBeSplitIntoFourDistinctStrings("aaaabbbbccccdddd")); console.log(canBeSplitIntoFourDistinctStrings("abcdefgh")); 

Output
No Yes Yes Yes 

Next Article
JavaScript Program to Check if Given String can be Split into Four Distinct Strings

P

parzival_op
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program
  • Geeks Premier League 2023

Similar Reads

    JavaScript Program for Word Break Problem
    The word break problem is a well-known and fundamental challenge within the field of computer science. The Word Break Problem in JavaScript involves determining if a given string can be segmented into words from a dictionary. It seeks to find a valid combination of dictionary words that compose the
    3 min read
    JavaScript Program to Split a String into a Number of Sub-Strings
    Given a string, the task is to split the string into number of sub-strings using JavaScript. This task is common in scenarios where data needs to be segmented or processed in chunks. This article provides a flexible solution that can divide a given string into a desired number of smaller substrings,
    2 min read
    Javascript Program to Check if a given string is Pangram or not
    In this article, we are going to implement algorithms to check whether a given string is a pangram or not. Pangram strings are those strings that contain all the English alphabets in them.Example: Input: “Five or six big jet planes zoomed quickly by tower.” Output: is a Pangram Explanation: Does'not
    7 min read
    How To Split a String Into Segments Of n Characters in JavaScript?
    When working with JavaScript, you might encounter a situation where you need to break a string into smaller segments of equal lengths. This could be useful when formatting a serial number, creating chunks of data for processing, or splitting a long string into manageable pieces. In this article, we
    6 min read
    How to Split a String into Equal Length Substrings in Java?
    In Java, splitting a string into smaller substrings of equal length is useful for processing large strings in manageable pieces. We can do this with the substring method of the loop. This method extracts a substring of the specified length from the input string and stores it in a list.Example:In the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences