JavaScript Program to Check if Given String can be Split into Four Distinct Strings
Last Updated :
18 Jul, 2024
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.
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");
}
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.`);
};
OutputString: "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
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"));
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"));
Similar Reads
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not. Examples: Input: str = "abccba", sc = "a",
3 min read
JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not
In this JavaScript article, we will see the solution to the problem of checking if a string follows the order of characters defined by a pattern or not. We have given a string and pattern as the input and our task is to develop a program that will check whether the input string follows the same patt
4 min read
JavaScript Program to Find the First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string. Examples: Input: âRavi had been saying that he had been thereâOutput: hadInput: âRavi had been saying thatâOutput: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUs
4 min read
JavaScript Program to Check Whether the String is Symmetrical or Not
In this article, we will see how to check whether the given string is symmetric or not. The symmetrical string is one that is similar from the starting to mid and mid to end. Example: Input: khokhoOutput: The entered string is symmetricalInput: madamOutput: The entered string is not symmetricalInput
3 min read
Group Strings Starting with Similar Number in JavaScript
Given an array of strings containing numbers at the beginning, the task is to group strings that start with the same number together. Examples: Input: arr = ["101apple", "202banana", "101orange", "303grape", "202mango", "101kiwi"];Output: [["101apple", "101orange", "101kiwi"],["202banana", "202mango
3 min read
JavaScript Program Count number of Equal Pairs in a String
In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analy
3 min read
JavaScript Program to Find Minimum Rotations Required to get the Same String
In this article, we are given a string str, our task is to find the minimum number of rotations required to get the same string using JavaScript. Example 1: Input: str = "geeks"Output: 5Explanation:i=1 : substring ="eekgeeks"i=2 : substring ="ekgeeks" i=3 : substring ="kgeeks"i=4 : substring ="kgee"
3 min read
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 Print the First Letter of Each Word
Printing the first letter of each word involves extracting the initial character from every word in a given string, typically accomplished by splitting the string into words and selecting the first character from each resulting word. Examples of Printing the First Letter of Each Word Table of Conten
3 min read
JavaScript Program to Match Single Character with Multiple Possibilities
In this article, we will write programs to check all possible matching in JavaScript. We will check the occurrence of characters individually in the given string or sequence. In this article, we will check the occurrence of vowels in the given string. Table of Content Using JavaScript RegExp test()
3 min read