Coding Interview Questions set 4

Let's begin with set 4,

9)Find the majority Element?

Given an array of size n, find the majority element. 

The majority element is the element that appears more than  n/2 times.


You may assume that the array is non-empty and the majority element always exists in the array.

Example 1:

Input: [4,2,4]

Output: 4

Example 2:

Input: [3,3,1,1,1,3,3]

Output: 3


var majorityElement = function(nums) {

var obj = {};

for(var i = 0; i < nums.length; i++){

obj[nums[i]] = obj[nums[i]] + 1 || 1;

if(obj[nums[i]] > nums.length / 2) {

return nums[i];



We have used an object map for maintaining the count.         


You may also like this articles:

 Coding Interview Set 1 

 Coding Interview Set 2.

10)Check if two strings are an anagram of each other?

2 words are anagram if 2nd word is formed by rearranging the letters from 1st word.  

Example 1:

Input: s = "anagram", t = "nagaram"

Output: true

Example 2:

Input: s = "rat", t = "car"

Output: false


function isAnagram(s, t) {

const map = {};

s.split('').map(c => map[c] = map[c] ? map[c] + 1 : 1);

t.split('').map(c => map[c] = map[c] ? map[c] - 1 : -1);

return Object.keys(map).every(k => map[k] === 0);



Here we have increased the count of each letter of one string using an object map and then decrease the count for the second string from the same map object.

If the map contains 0 counts for each letter that means it is an anagram

I hope you like this article. Please stay connected for set 5.

You can also follow me on Twitter or Linkedin for the latest updates.

Written By:

Saurabh Joshi


Popular Posts