### 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.

Assumptions:

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

Solution:

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];

}};

Logic:

We have used an object map for maintaining the count.

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

Solution:

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);

}

Logic:

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

Written By:

Saurabh Joshi