JavaScript Program to Check if Kth Index Elements are Unique
Last Updated :
29 Aug, 2024
In this article, We have given a String list and a Kth index in which we have to check that each item in a list at that particular index should be unique. If they all are unique then we will print true in the console else we will print false in the console.
Example:
Input: test_list = [“gfg”, “best”, “for”, “geeks”], K = 1 .
Output: False
Explanation: e occurs as 1st index in both best and geeks.
Input: test_list = [“gfg”, “best”, “geeks”], K = 2
Output: True
Explanation: g, s, e, all are unique.
These are the following approaches by using these we can solve this question:
Using for Loop
In this approach, we iterate for each string and check whether the character is present in the empty array or not. if the character is present in the 'res' array it means the value is not unique and it will return false else it will iterate the whole array check for the unique array and return true.
Example: This example shows the use of the above-explained approach.
JavaScript
// Initializing list
let test_list = ["gfg", "best", "for", "geeks"];
// Printing original list
console.log("The original list is : " + test_list);
// Initializing K
let K = 2;
let res = [];
let flag = true;
for (let i = 0; i < test_list.length; i++) {
let ele = test_list[i];
// Checking if element is repeated
if (res.includes(ele.charAt(K))) {
flag = false;
break;
} else {
res.push(ele.charAt(K));
}
}
// Printing result
console.log("Is Kth index all unique : " + flag);
OutputThe original list is : gfg,best,for,geeks
Is Kth index all unique : true
In this approach, we are checking if the characters at the 2nd index in the array test_list are unique. It initializes a count object to store character occurrences, then checks if all counts are less than 2 using every(). It prints "Is Kth index all unique : true" if all characters are unique, and "Is Kth index all unique : false" otherwise.
Example: This example shows the use of the above-explained approach.
JavaScript
// Initializing list
let test_list = ["gfg", "best", "for", "geeks"];
// Printing original list
console.log("The original list is : " + test_list);
// Initializing K
let K = 2;
// Getting count of each Kth index item
let count = {};
for (let i = 0; i < test_list.length; i++) {
let sub = test_list[i];
let char = sub.charAt(K);
count[char] = (count[char] || 0) + 1;
}
// Extracting result
let res = Object.values(count).every((val) => val < 2);
// Printing result
console.log("Is Kth index all unique : " + res);
OutputThe original list is : gfg,best,for,geeks
Is Kth index all unique : true
Using Set and Array Filter
In this approach, we can utilize a Set data structure to keep track of unique characters at the Kth index of each string in the given list. We iterate through the list, extract the character at the Kth index of each string, and add it to the Set. If any character is already present in the Set, it indicates that there is a duplicate, and we return false. Otherwise, we return true if all characters are unique.
Example:
JavaScript
// Initialize the list
let test_list = ["gfg", "best", "for", "geeks"];
// Print the original list
console.log("The original list is: " + test_list);
// Initialize K
let K = 2;
// Use Set to store unique characters
let charSet = new Set();
// Iterate through the list and check for uniqueness
let isUnique = test_list.every((str) => {
let char = str.charAt(K);
if (charSet.has(char)) {
return false; // If character is already present, return false
} else {
charSet.add(char); // Add character to Set
return true;
}
});
// Print the result
console.log("Is Kth index all unique: " + isUnique);
OutputThe original list is: gfg,best,for,geeks
Is Kth index all unique: true
Using Set and Array Filter
In this approach, we can utilize a Set data structure to keep track of unique characters at the Kth index of each string in the given list. We iterate through the list, extract the character at the Kth index of each string, and add it to the Set. If any character is already present in the Set, it indicates that there is a duplicate, and we return false. Otherwise, we return true if all characters are unique.
Example:
JavaScript
function areKthIndexCharactersUnique(test_list, K) {
const uniqueSet = new Set();
for (let i = 0; i < test_list.length; i++) {
// Check if Kth index is within the bounds of the string
if (K >= test_list[i].length) {
continue;
}
const char = test_list[i][K];
if (uniqueSet.has(char)) {
return false; // Character already exists in the set, not unique
}
uniqueSet.add(char);
}
return true; // All characters at Kth index are unique
}
// Examples
const test_list1 = ["gfg", "best", "for", "geeks"];
const K1 = 1;
console.log(areKthIndexCharactersUnique(test_list1, K1)); // Output: False
const test_list2 = ["gfg", "best", "geeks"];
const K2 = 2;
console.log(areKthIndexCharactersUnique(test_list2, K2))
Using a Hash Map for Frequency Counting
In this approach, we utilize a hash map (JavaScript object) to keep track of the frequency of characters at the Kth index of each string in the given list. This method involves iterating through the list and updating the frequency count of each character. If any character's frequency becomes greater than 1, we return false. Otherwise, after the iteration, we return true if all characters are unique.
Example:
JavaScript
function areKthIndicesUnique(test_list, K) {
let charFrequency = {};
for (let str of test_list) {
if (str.length > K) {
let char = str[K];
if (charFrequency[char]) {
return false;
} else {
charFrequency[char] = 1;
}
}
}
return true;
}
let test_list1 = ["gfg", "best", "for", "geeks"];
let K1 = 1;
console.log(areKthIndicesUnique(test_list1, K1));
let test_list2 = ["gfg", "best", "geeks"];
let K2 = 2;
console.log(areKthIndicesUnique(test_list2, K2));
Using Array.reduce() and Array.some() Methods
- Initialize a Set: Use a Set to store characters encountered at the Kth index.
- Use Array.reduce(): Traverse the list and accumulate characters into the Set . If a character is already present in the Set , it indicates a duplicate.
- Check Uniqueness: Use Array.some() to efficiently check if a character at the Kth index is already in the Set .
Steps:
- Create a Set: For storing characters found at the Kth index.
- Traverse the List: Use Array.reduce() to check if characters are unique while building the Set .
- Return Result: If duplicates are found during the iteration, return false . If all characters are unique, return true .
Example:
JavaScript
function areKthIndexCharactersUnique(test_list, K){
const uniqueChars = new Set();
const isUnique = test_list.reduce((isUnique, str) => {
if (str.length > K) {
const char = str[K];
if (uniqueChars.has(char)) {
return false;
}
else {
uniqueChars.add(char);
}
}
return isUnique;
}, true);
return isUnique;
}
const test_list1 = [ "gfg", "best", "for", "geeks" ];
const K1 = 1;
console.log(areKthIndexCharactersUnique(test_list1, K1));
const test_list2 = [ "gfg", "best", "geeks" ];
const K2 = 2;
console.log(areKthIndexCharactersUnique(test_list2, K2));
Similar Reads
JavaScript Program to Check if an Array Contains only Unique Values
In this article, we are given an array, Our task is to find whether the elements in an array are unique or not.Examples:Input 1: 7,8,1,5,9 Output: true Input2: 7,8,1,5,5 Output: falseIn Input 1, elements 7,8,1,5,9 are distinct from each other and they were unique, there was no repetition of elements
4 min read
JavaScript Program to Find all Elements that Appear More than n/k Times
We are given an array that has n number of elements and an integer k, we have to return all the elements which will appear more than n/k times in the array using JavaScript. Examples:Input: arr = {4, 2, 4, 1, 4, 5, 5, 5}, k=3Output: {4 , 5}Explanation: The elements {4, 5} appears more than n/k i.e.
3 min read
JavaScript Program to Count Distinct Elements in Every Window
In this problem we are given an array of integers and a number M. We have to find the count of distinct elements in every window of size M in the array using JavaScript. Example: Input: arr[] = [1, 2, 1, 3, 4, 2, 3], K = 4Output: 3 4 4 3Explanation: First window is [1, 2, 1, 3], count of distinct nu
4 min read
First Element to Occur K Times using JavaScript
Given an array and number, our task is to find the first element that occurs exactly k times in an array using JavaScript. Example: Input: array= [1, 2, 3, 4, 2, 5, 6, 4, 2] and k = 3.Output: 2Explanation: Here the first element that occurred 3 times in the array is 2Table of Content Using nested fo
3 min read
JavaScript Program to Find the First Non-Repeated Element in an Array
Finding the first non-repeated element in an array refers to identifying the initial occurrence of an element that does not occur again elsewhere within the array, indicating uniqueness among the elements.Examples: Input: {-1, 2, -1, 3, 0}Output: 2Explanation: The first number that does not repeat i
5 min read
JavaScript Program to Find Kâth Non-Repeating Character in String
The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps
6 min read
Javascript Program for Last duplicate element in a sorted array
We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7}Output :Last index: 4Last duplicate item: 6Input :
3 min read
JavaScript Program to Print All Distinct Elements in an Integer Array
Given an Array of Integers consisting of n elements with repeated elements, the task is to print all the distinct elements of the array using JavaScript. We can get the distinct elements by creating a set from the integer array. Examples: Input : arr = [ 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9 ] Outpu
3 min read
JavaScript - How To Find Unique Characters of a String?
Here are the various methods to find the unique characters of a string in JavaScript.1. Using Set (Most Common)The Set object is one of the easiest and most efficient ways to find unique characters. It automatically removes duplicates.JavaScriptconst s1 = "javascript"; const s2 = [...new Set(s1)]; c
3 min read
JavaScript Program to Find Element that Appears once in Array where Other Elements Appears Twice
Given an Array of Integers consisting of n elements where each element appears twice except one element. The task is to find the element which appears only once in the input array in JavaScript. Example: Input : arr = [ 5, 9, 2, 7, 4, 8, 6, 1, 5, 1, 4, 6, 3, 7, 8, 2, 9 ] Output : 3Explanation: The i
3 min read