Count elements in Array appearing only once and don’t have its consecutive next and previous present
Given an array arr[]. The task is to count elements in the array that appears only once and it’s consecutive next (arr[i]+1) and prev (arr[I] – 1) elements are not present in the array.
Examples
Input: arr[] = {7, 3, 1, 4, 5, 3, 4}
Output: 2
Explanation: Numbers 7 and 1 follows the given condition. Hence the answer is 2.
Input: arr = {10, 6, 5, 8}
Output: 2
Naive Approach:
The naive approach to solve the problem is to use two nested loops to find for each element whether they are unique or not. If an element is unique, then again iterate entire array within the same outer loop which we used to find uniqueness, to find whether it’s consecutive next (arr[i]+1) and prev (arr[I] – 1) elements are present or not in the array. If they are not present increment the count.
Algorithm:
- Initialize count to 0.
- Traverse each element from i = 0 to n – 1
- Initialize unique to true
- Traverse each element from j = 0 to n – 1
i. If i is not equal to j and arr[i] is equal to arr[j], then set unique to false and break inner loop
- If unique is true, then
i. Initialize next to false and prev to false
ii. Traverse each element from j = 0 to n – 1
a. If arr[j] is equal to arr[i] + 1, then set next to true
b. If arr[j] is equal to arr[i] – 1, then set prev to true
iii. If next is false and prev is false, then increment count
- Return count.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countElements( int arr[], int n) {
int count = 0;
for ( int i = 0; i < n; i++) {
bool unique = true ;
for ( int j = 0; j < n; j++) {
if (i != j && arr[i] == arr[j]) {
unique = false ;
break ;
}
}
if (unique) {
bool next = false , prev = false ;
for ( int j = 0; j < n; j++) {
if (arr[j] == arr[i] + 1)
next = true ;
if (arr[j] == arr[i] - 1)
prev = true ;
}
if (!next && !prev)
count++;
}
}
return count;
}
int main() {
int arr[] = { 10, 6, 5, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
int count = countElements(arr, n);
cout << count;
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
public static int countElements( int [] arr, int n)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
boolean unique = true ;
for ( int j = 0 ; j < n; j++) {
if (i != j && arr[i] == arr[j]) {
unique = false ;
break ;
}
}
if (unique) {
boolean next = false , prev = false ;
for ( int j = 0 ; j < n; j++) {
if (arr[j] == arr[i] + 1 )
next = true ;
if (arr[j] == arr[i] - 1 )
prev = true ;
}
if (!next && !prev)
count++;
}
}
return count;
}
public static void main(String[] args)
{
int [] arr = { 10 , 6 , 5 , 8 };
int n = arr.length;
int count = countElements(arr, n);
System.out.println(count);
}
}
|
Python
def count_elements(arr, n):
count = 0
for i in range (n):
unique = True
for j in range (n):
if i ! = j and arr[i] = = arr[j]:
unique = False
break
if unique:
next_element, prev_element = False , False
for j in range (n):
if arr[j] = = arr[i] + 1 :
next_element = True
if arr[j] = = arr[i] - 1 :
prev_element = True
if not next_element and not prev_element:
count + = 1
return count
if __name__ = = "__main__" :
arr = [ 10 , 6 , 5 , 8 ]
n = len (arr)
count = count_elements(arr, n)
print (count)
|
C#
using System;
public class GFG {
public static int CountElements( int [] arr, int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
bool unique = true ;
for ( int j = 0; j < n; j++) {
if (i != j && arr[i] == arr[j]) {
unique = false ;
break ;
}
}
if (unique) {
bool next = false , prev = false ;
for ( int j = 0; j < n; j++) {
if (arr[j] == arr[i] + 1)
next = true ;
if (arr[j] == arr[i] - 1)
prev = true ;
}
if (!next && !prev)
count++;
}
}
return count;
}
public static void Main()
{
int [] arr = { 10, 6, 5, 8 };
int n = arr.Length;
int count = CountElements(arr, n);
Console.WriteLine(count);
}
}
|
Javascript
function countElements(arr, n) {
let count = 0;
for (let i = 0; i < n; i++) {
let unique = true ;
for (let j = 0; j < n; j++) {
if (i !== j && arr[i] === arr[j]) {
unique = false ;
break ;
}
}
if (unique) {
let next = false ;
let prev = false ;
for (let j = 0; j < n; j++) {
if (arr[j] === arr[i] + 1)
next = true ;
if (arr[j] === arr[i] - 1)
prev = true ;
}
if (!next && !prev)
count++;
}
}
return count;
}
const arr = [10, 6, 5, 8];
const n = arr.length;
const count = countElements(arr, n);
console.log(count);
|
Time Complexity: O(N*N) as two nested loops are executing both from 1 to N where N is the size of input array.
Space Complexity: O(1) as no extra space has been taken.
Approach: This problem can be solved by using HashMaps. Store the frequency of each number in hashmap and then traverse the array to check for uniqueness of the current element and occurrence of its consecutive next and previous elements.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int count(vector< int >& nums)
{
int n = nums.size();
map< int , int > m;
for ( int i = 0; i < n; i++) {
if (m.find(nums[i]) == m.end())
m.insert({ nums[i], 1 });
else
m[nums[i]]++;
}
int c = 0;
for ( auto i : m) {
int p = i.first;
if (m.find(p + 1) == m.end()
&& m.find(p - 1) == m.end()
&& i.second == 1)
c++;
}
return c;
}
int main()
{
vector< int > arr = { 10, 6, 5, 8 };
cout << count(arr);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static int count(ArrayList<Integer> nums)
{
int n = nums.size();
Map<Integer, Integer> m
= new HashMap<Integer, Integer>();
for ( int i = 0 ; i < n; i++) {
if (m.containsKey(nums.get(i)) == false )
m.put(nums.get(i), 1 );
else
m.put(nums.get(i), m.get(nums.get(i)) + 1 );
}
int c = 0 ;
for (Map.Entry<Integer, Integer> i : m.entrySet()) {
int p = i.getKey();
if (m.containsKey(p + 1 ) == false
&& m.containsKey(p - 1 ) == false
&& i.getValue() == 1 )
c++;
}
return c;
}
public static void main(String[] args)
{
ArrayList<Integer> arr
= new ArrayList<>(Arrays.asList( 10 , 6 , 5 , 8 ));
System.out.print(count(arr));
}
}
|
Python3
def count(nums):
n = len (nums)
m = {}
for i in range ( 0 , n):
if nums[i] not in m:
m[nums[i]] = 1
else :
m[nums[i]] + = 1
c = 0
for i in m:
p = i
if ( not m.__contains__(p + 1 )
and not m.__contains__(p - 1 )
and m[i] = = 1 ):
c + = 1
return c
arr = [ 10 , 6 , 5 , 8 ]
print (count(arr))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
static int count(ArrayList nums)
{
int n = nums.Count;
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
if (m.ContainsKey(( int )nums[i]) == false )
m.Add(( int )nums[i], 1);
else
m[( int )nums[i]] = m[( int )nums[i]] + 1;
}
int c = 0;
foreach (KeyValuePair< int , int > i in m)
{
int p = i.Key;
if (m.ContainsKey(p + 1) == false
&& m.ContainsKey(p - 1) == false
&& i.Value == 1) {
c++;
}
}
return c;
}
public static void Main()
{
ArrayList arr = new ArrayList();
arr.Add(10);
arr.Add(6);
arr.Add(5);
arr.Add(8);
Console.Write(count(arr));
}
}
|
Javascript
<script>
const count = (nums) => {
let n = nums.length;
let m = {};
for (let i = 0; i < n; i++) {
if (!(nums[i] in m))
m[nums[i]] = 1;
else
m[nums[i]]++;
}
let c = 0;
for (let i in m) {
let p = parseInt(i);
if ((!(p + 1 in m)) && (!(p - 1 in m)) && m[i] == 1)
c++;
}
return c;
}
let arr = [10, 6, 5, 8];
document.write(count(arr));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
23 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...