-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmissingandrepeatingnumber.cpp
More file actions
79 lines (63 loc) · 1.66 KB
/
missingandrepeatingnumber.cpp
File metadata and controls
79 lines (63 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Given an unsorted array of size n. Array elements are in the range of 1 to n. One number from set {1, 2, …n} is missing and one number occurs twice in the array. Find these two numbers.
Examples:
Input: arr[] = {3, 1, 3}
Output: Missing = 2, Repeating = 3
Explanation: In the array, 2 is missing and 3 occurs twice
// C++ program to Find the repeating
// and missing elements
#include <bits/stdc++.h>
using namespace std;
void printTwoElements(int arr[], int size)
{
int i;
cout << "The repeating element is ";
for (i = 0; i < size; i++) {
if (arr[abs(arr[i]) - 1] > 0)
arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
else
cout << abs(arr[i]) << "\n";
}
cout << "and the missing element is ";
for (i = 0; i < size; i++) {
if (arr[i] > 0)
cout << (i + 1);
}
}
/* Driver code */
int main()
{
int arr[] = { 7, 3, 4, 5, 5, 6, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
printTwoElements(arr, n);
}
// This code is contributed by Shivi_Aggarwal
// Java program to Find the repeating
// and missing elements
import java.io.*;
class GFG {
static void printTwoElements(int arr[], int size)
{
int i;
System.out.print("The repeating element is ");
for (i = 0; i < size; i++) {
int abs_val = Math.abs(arr[i]);
if (arr[abs_val - 1] > 0)
arr[abs_val - 1] = -arr[abs_val - 1];
else
System.out.println(abs_val);
}
System.out.print("and the missing element is ");
for (i = 0; i < size; i++) {
if (arr[i] > 0)
System.out.println(i + 1);
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 7, 3, 4, 5, 5, 6, 2 };
int n = arr.length;
printTwoElements(arr, n);
}
}
// This code is contributed by Gitanjali