Checking for Duplicate Strings in JavaScript Array
Last Updated :
03 May, 2024
Checking for duplicate strings in a JavaScript array involves identifying if there are any repeated string values within the array. Given an array of strings a with size N, find all strings that occur more than once. If none is found, return [-1].
Example:
Input:
N = 4
arr = ['apple', 'banana', 'orange', 'apple']
Output :
[ 'apple' ]
Explanation :
There is only 'apple' is repeating 2 times therefore output is 'apple' in given array.
Using Iteration
In this approach, iterate through the array and compare each element with every other element to detect duplicates. This method has a time complexity of O(n^2) as it involves nested iteration over the array, making it less efficient for large datasets.
Example: Implementation to check for duplicate strings in JavaScript array using simple iteration.
JavaScript
function duplicateStr(arr) {
let res = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
res.push(arr[i]);
}
}
}
if (res.length == 0) res.push(-1);
return res;
}
const array = ['apple', 'banana', 'orange', 'apple'];
console.log(duplicateStr(array));
Time complexity: 0( n2 )
Space complexity: 0( 1 )
Using Set
Utilize a Set data structure to store unique elements. While iterating through the array, check if the element already exists in the Set.
Example: Implementation to check for duplicate strings in JavaScript array using set.
JavaScript
function duplicatesStr(arr) {
const set = new Set();
const res = [];
for (let item of arr) {
if (set.has(item)) {
res.push(item);
}
else set.add(item);
}
res.length == -1 && res.push(-1);
return res;
}
const array = ["apple", "orange", "apple", "mango", "banana", "kiwi", "banana"];
console.log(duplicatesStr(array));
Output[ 'apple', 'banana' ]
Time complexity: 0( n )
Space complexity: 0 ( n )
Using Sorting
In the sorting approach, begin by sorting the array. Then, iterate through it and check if adjacent elements are identical. This method offers a time complexity of O(n log n) due to the sorting operation, followed by a linear iteration to identify duplicates, providing an efficient means for duplicate detection in arrays.
Example: Implementation to check for duplicate strings in JavaScript array using sorting method.
JavaScript
function duplicatesStr(arr) {
arr.sort();
const res = [];
for (let i = 0; i < arr.length - 1; i++) {
let flage = false;
while (i < arr.length && arr[i] === arr[i + 1]) {
flage = true;
i++;
}
if (flage) res.push(arr[i]);
}
res.length == 0 && res.push(-1);
return res;
}
const array = ["apple", "banana", "orange",
"apple", "mango", "banana", "kiwi", "banana"];
console.log(duplicatesStr(array));
Output[ 'apple', 'banana' ]
Time complexity: 0(n log n)
Space complexity: 0( 1 )
Frequency counting
In the frequency counting approach, utilize an object to store the frequency of each string in the array. Then, return an array of strings that have a frequency greater than one. This method offers a time complexity of O(n) as it involves a single iteration over the array to count frequencies, providing an efficient solution for identifying duplicate strings.
Example: Implementation to check for duplicate strings in JavaScript array using frequency counting method.
JavaScript
function duplicatesStr(arr) {
const freqMap = {};
for (let item of arr) {
if (item in freqMap) freqMap[item]++;
else freqMap[item] = 1;
}
const res = [];
for (const key in freqMap) {
if (freqMap[key] > 1) res.push(key);
}
if (res.length == 0) res.push(-1);
return res;
}
const array = ["apple", "banana", "orange", "apple",
"mango", "banana", "apple", "banana", "orange",
"apple", "mango", "banana"];
console.log(duplicatesStr(array));
Output[ 'apple', 'banana', 'orange', 'mango' ]
Time complexity: 0( n )
Space complexity: 0 ( n )
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read