LeetCode 30 day Challenge | Day 7 | Counting Elements | LeetCode #1426

preview_player
Показать описание
**** Best Books For Data Structures & Algorithms for Interviews:**********
*****************************************************************************

LeetCode 30 day Challenge | Problem 7 | Counting Elements | 7 April
Facebook Coding Interview question,
google coding interview question,
leetcode,
counting elements,

#Amazon #Facebook #CodingInterview #LeetCode #CountingElements #30DayChallenge #Google
Рекомендации по теме
Комментарии
Автор

Please share if you have other solutions.

KnowledgeCenter
Автор

Simple solution using C++ and unordered set
class Solution {
public:
int countElements(vector<int>& arr) {
unordered_set<int> st;
int count = 0;
int n = arr.size();
for(int i = 0; i < n; i++)
st.insert(arr[i]);
for(int i = 0; i < n; i++){
int sum = arr[i] + 1;
if(st.find(sum) != st.end())
count++;
}
return count;
}
};

swapnilkant
Автор

Thanks for the explanation. The content is really great. I understood the concept of the problem and wrote the code myself.

SuhasGowda
Автор

No Need of a HashMap, It can be easily done with HashSet. Put all the elements in a HashSet and trace back the array and look for arr[i]+1 value.

kundankumar
Автор

Use a Hash Set to store the elements and loop again to get the valid count.


Code in Java: Accepted


class Solution
{
public int countElements(int[] arr)
{
int count = 0;
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < arr.length; i++)
{
set.add(arr[i]);
}

for(int i = 0; i < arr.length; i++)
{
if(set.contains(arr[i]+1))
{
count++;
}
}
return count;
}
}

triveninaik
Автор

why use a map...! a HashSet would be enough for this problem.

ojaswachaurasia
Автор

How about below scala solution? Any suggestions?


def countElements (array: Array[Int]): Int = {
var counter = 0
val newArray = array map (_ + 1) // increment each element in array

for (i <- newArray indices) {
if (array contains newArray(i)) counter += 1
}

counter
}

simplecop
Автор

I actually tryna avoid using Hashmap. Instead, I sorted the array and then counted the numbers which are the same. IF the arr[i+1] number is equal to the arr[i]+1 number then res+=counted and counted=0 at the same time. If the arr[i+1] number is not equal to the arr[i]+1 number then counted=0 only. Although my code's runtime is a bit slower than the hashmap way, it goes with O(1) space complexity.

luongthangnguyen
Автор

Used Java Hashmap,


public int countElements(int[] arr) {
Map<Integer, Integer> map = new HashMap();
for(int n : arr){
if(map.containsKey(n)){
map.put(n, map.get(n) + 1);
}else{
map.put(n, 1);
}
}
int result = 0;
for(int n : arr){
if(map.containsKey(n+1)){
result++;
}
}
return result;
}

banuchandar
Автор

count=0
for x in arr:
if x+1 in arr:
count=count+1
return count

abhiseka