Finding repeating and missing numbers Using array manipulation
In this approach, we will use a nested loop to return repeating and missing numbers. We will use a loop from 1 to N range. We use another loop inside it to store the count of each number. We will return the repeating number which has a count of 2 and return the missing number which has a count of 0 (not present).
Example: This JavaScript code efficiently identifies a repeating and a missing number within an array using array manipulation and negation, ensuring a concise and effective solution.
Javascript
function MissingandRepeating(vec) { const n = vec.length; // size of the array let repeating = -1, missing = -1; // Find the repeating and missing number in the array for (let i = 0; i < n; i++) { const index = Math.abs(vec[i]) - 1; if (vec[index] < 0) repeating = Math.abs(vec[i]); else vec[index] = -vec[index]; } for (let i = 0; i < n; i++) { if (vec[i] > 0) { missing = i + 1; break ; } } return [repeating, missing]; } const vec = [1 , 2, 4 , 5, 5, 6 , 7]; const ans = MissingandRepeating(vec); console.log( "The repeating and missing numbers are: {" + ans[0] + ", " + ans[1] + "}" ); |
The repeating and missing numbers are: {5, 3}
Time Complexity: O(n) , because we are using a nested loop to store the count of elements.
Space Complexity: O(1) , as it is taking constant time.
Find the Repeating & Missing Numbers in JavaScript Array ?
JavaScript allows us to find the repeating and missing number in a given array which includes numbers from 1 to N range. We are given an array that has numbers present from 1 to N range, where N is any natural number. One number is present two times and one number is missing from the range.
We have to return these numbers which can be achieved by several methods using JavaScript which are as follows:
Table of Content
- Using array manipulation
- Using Hashing