Coding Problem 5: Find element occuring once when all other are present thrice [GFG - Problem Solving]

 Given an array of integers arr[] of length N, every element appears thrice except for one which occurs once.

Find that element which occurs once.

Example 1:

Input:
N = 4
arr[] = {1, 10, 1, 1}
Output:
10
Explanation:
10 occurs once in the array while the other
element 1 occurs thrice.

Example 2:

Input:
N = 10
arr[] = {3, 2, 1, 34, 34, 1, 2, 34, 2, 1}
Output:
3
Explanation:
All elements except 3 occurs thrice in the array.

Your Task:
You do not need to take any input or print anything. You task is to complete the function singleElement() which takes an array of integers arr and an integer N which finds and returns the element occuring once in the array.

Constraints:
1 ≤ N ≤ 105
-109 ≤ A[i] ≤ 109

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).


Solution :

Repository: coding-problems: https://github.com/nileshkadam222/coding-problems/blob/master/src/com/coding/problems/gfg/ElementOccuringOnce.java


package com.coding.problems.gfg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

class ElementOccuringOnceSolution {

static int singleElement(int[] arr, int n) {
// code here
Map<Integer, Integer> countingMap = new HashMap<>();
Arrays.stream(arr).forEach(f -> {
if (countingMap.containsKey(f)) {
int data = countingMap.get(f);
countingMap.put(f, data + 1);
} else {
countingMap.put(f, 1);
}
});
return countingMap.entrySet().stream().filter(f-> f.getValue() == 1).map(m -> m.getKey()).findFirst().get();
}
}

public class ElementOccuringOnce {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(reader.readLine());
while (t-- > 0) {
int n = Integer.parseInt(reader.readLine());
String[] s = reader.readLine().split(" ");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(s[i]);
}
ElementOccuringOnceSolution solution = new ElementOccuringOnceSolution();
int ans = solution.singleElement(arr, n);
System.out.println(ans);
}

}
}

Comments

Popular posts from this blog

Primitive Data Types in java

let - Keyword in JavaScript (Block scope)

Coding Problem 4: Smallest window containing 0, 1 and 2 [GFG - Problem Solving]