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 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
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 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 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
Unique Windows Directory Program in Java In the Windows filesystem, two folders/files cannot have the same name. If you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique. Problem Statement
2 min read
Counting Distinct elements after Range of Operations Given an integer K and array A[] of size N, count the number of distinct elements after performing an operation on every array index. For each i (0 ⤠i ⤠N - 1), we can perform one of the following operations exactly once: Add K to A[i]Subtract K from A[i]Leave A[i] as it is.Examples: Input: N = 6,
7 min read
Count same Value Pairs with Minimum Separation Given an array a[] of size n and integer k. The task is to count a number of different pairs of indexes where values at a given index are the same and both indexes are at least k indices apart. Examples: Input: n = 5, k = 2 a = {1, 2, 2, 1, 2} Output: 3Explanation: Possible pairs are found in indice
6 min read
Check if all array elements are distinct Given an array, check whether all elements in an array are distinct or not. Examples: Input : 1, 3, 2, 4Output : Yes Input : "Geeks", "for", "Geeks"Output : No Input : "All", "Not", "Equal"Output : Yes One simple solution is to use two nested loops. For every element, check if it repeats or not. If
4 min read
k-th distinct (or non-repeating) element among unique elements in an array. Given an integer array arr[], print kth distinct element in this array. The given array may contain duplicates and the output should print the k-th element among all unique elements. If k is more than the number of distinct elements, print -1.Examples:Input: arr[] = {1, 2, 1, 3, 4, 2}, k = 2Output:
7 min read