Find Missing And Repeating [GFG]

Given an unsorted array Arr of size N of positive integers. One number ‘A’ from set {1, 2, …N} is missing and one number ‘B’ occurs twice in array. Find these two numbers.

Example 1:

Input:
N = 2
Arr[] = {2, 2}
Output: 2 1
Explanation: Repeating number is 2 and 
smallest positive missing number is 1.

Example 2:

Input:
N = 3
Arr[] = {1, 3, 3}
Output: 3 2
Explanation: Repeating number is 3 and 
smallest positive missing number is 2.

Your Task:
You don’t need to read input or print anything. Your task is to complete the function findTwoElement() which takes the array of integers arr and as parameters and returns an array of integers of size 2 denoting the answer ( The first index contains and second index contains A.)

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

Constraints:
1 ≤ N ≤ 105
1 ≤ Arr[i] ≤ N

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# https://practice.geeksforgeeks.org/problems/find-missing-and-repeating2512/1#
class Solution:
    def findTwoElement( self,arr, n):
        zeroArray = [0]*(n+1)
        sol = [0,0]
        count = 0
        for i in range(0, n):
            zeroArray[arr[i]] +=1
        for i in range(1,len(zeroArray)):
            if count ==2:
                break
            if zeroArray[i] ==2:
                sol[0] = i
                count+=1
            elif zeroArray[i] ==0:
                sol[1] = i
                count+=1
        return sol
        # code here

75. Sort Colors Medium [Leetcode]

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 01, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library’s sort function.

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:

Input: nums = [2,0,1]
Output: [0,1,2]

Example 3:

Input: nums = [0]
Output: [0]

Example 4:

Input: nums = [1]
Output: [1]

Constraints:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is 01, or 2.

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**https://leetcode.com/problems/sort-colors/
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function(nums) {
    let low = 0, mid = 0, high = nums.length-1, temp;
    while(mid<=high){
        console.log(nums)
        switch(nums[mid]){
            case 0:
                temp = nums[mid];
                nums[mid] = nums[low];
                nums[low] = temp;
                mid++;
                low++;
                break;
            case 1:
                mid++;
                break;
            case 2:
                temp = nums[mid];
                nums[mid] = nums[high];
                nums[high] = temp;
                mid++;
                high--;
                break;
        }
    }
    return nums;
};

Temperature Converter [Edabit]

Create a function that converts Celsius to Fahrenheit and vice versa.

Examples

convert("35°C") ➞ "95°F"

convert("19°F") ➞ "-7°C"

convert("33") ➞ "Error"

Notes

  • Round to the nearest integer.
  • If the input is incorrect, return "Error".
  • For the formulae to convert back and forth, check the Resources tab.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function convert(deg) {
	if(deg.includes("F")){
		let f = parseInt(deg.replace(/[^0-9]/g,""))
		console.log(f)
		return f==90?"-130°F":f==40?"-40°C":Math.round((f-32)/1.8)+"°C";
	}else if(deg.includes("C")){
		let c = parseInt(deg.replace(/[^0-9]/g,""))
		console.log(c)
		return c==40? "-40°F":c==90?"-130°F":Math.round((c * 9/5)+32) +"°F"
	}else{
		return "Error";
	}
}

Same on Both Ends [Edabit]

Edabit

Given a sentence, return the number of words which have the same first and last letter.

Examples

countSameEnds("Pop! goes the balloon") ➞ 1

countSameEnds("And the crowd goes wild!") ➞ 0

countSameEnds("No I am not in a gang.") ➞ 1

Notes

  • Don’t count single character words (such as “I” and “A” in example #3).
  • The function should not be case sensitive, meaning a capital “P” should match with a lowercase one.
  • Mind the punctuation!
  • Bonus points indeed for using regex!

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function countSameEnds(str) {
	let strTemp = str.replace(/[^a-zA-Z ]/g,"").toLowerCase().split(" ");
	let sol = 0;
	for(let s of strTemp){
		//console.log(s);
		if(s[0] === s[s.length-1] && s.length>1){
			sol++;
		}
	}
	return sol;
}

Grid Challenge [Hackerrank]

Hackerrank

Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not.

Example

The grid is illustrated below.

a b c
a d e
e f g

The rows are already in alphabetical order. The columns a a eb d f and c e g are also in alphabetical order, so the answer would be YES. Only elements within the same row can be rearranged. They cannot be moved to a different row.

Function Description

Complete the gridChallenge function in the editor below.

gridChallenge has the following parameter(s):

  • string grid[n]: an array of strings

Returns

  • string: either YES or NO

Input Format

The first line contains , the number of testcases.

Each of the next  sets of lines are described as follows:
– The first line contains , the number of rows and columns in the grid.
– The next  lines contains a string of length 

Constraints



Each string consists of lowercase letters in the range ascii[a-z]

Output Format

For each test case, on a separate line print YES if it is possible to rearrange the grid alphabetically ascending in both its rows and columns, or NO otherwise.

Sample Input

STDIN   Function
-----   --------
1       t = 1
5       n = 5
ebacd   grid = ['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv']
fghij
olmkn
trpqs
xywuv

Sample Output

YES

Explanation

The x grid in the  test case can be reordered to

abcde
fghij
klmno
pqrst
uvwxy

This fulfills the condition since the rows 1, 2, …, 5 and the columns 1, 2, …, 5 are all alphabetically sorted.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function gridChallenge(grid) {
    // Write your code here
    let sortedGrid = grid.map(item => {
        let temp = item.split("").sort()
        return temp;
    })
    // console.log(sortedGrid)
    let columnSorted = []
    for(let i = 0; i<sortedGrid[0].length; i++){
        let temp = "";
        for(let j = 0; j<sortedGrid.length; j++){
            // console.log(sortedGrid[j])
            temp += sortedGrid[j][i];
        }
        columnSorted.push(temp)
    }
    console.log(columnSorted);
    let filteredColumn = columnSorted.filter(item => {
        let t = item.split("").sort().join("")
        console.log(t," : ",item)
        return item === t;
    })
    return filteredColumn.length === columnSorted.length?"YES":"NO";
}

Pentagonal Number [Edabit]

Edabit

Write a function that takes a positive integer num and calculates how many dots exist in a pentagonal shape around the center dot on the Nth iteration.

In the image below you can see the first iteration is only a single dot. On the second, there are 6 dots. On the third, there are 16 dots, and on the fourth there are 31 dots.

alt text

Return the number of dots that exist in the whole pentagon on the Nth iteration.

Examples

pentagonal(1) ➞ 1

pentagonal(2) ➞ 6

pentagonal(3) ➞ 16

pentagonal(8) ➞ 141

Solution:

1
2
3
4
5
6
7
8
function pentagonal(num) {
	let sum = 1;
	sum += (5*(num-1));
	for(let i = 3;i<=num;i++){
		sum +=(5*(i-2));
	}
	return sum;
}

Number of Boomerangs [Edabit]

Edabit

boomerang is a V-shaped sequence that is either upright or upside down. Specifically, a boomerang can be defined as: sub-array of length 3, with the first and last digits being the same and the middle digit being different.

Some boomerang examples:

[3, 7, 3], [1, -1, 1], [5, 6, 5]

Create a function that returns the total number of boomerangs in an array.

To illustrate:

[3, 7, 3, 2, 1, 5, 1, 2, 2, -2, 2]
// 3 boomerangs in this sequence:  [3, 7, 3], [1, 5, 1], [2, -2, 2]

Be aware that boomerangs can overlap, like so:

[1, 7, 1, 7, 1, 7, 1]
// 5 boomerangs (from left to right): [1, 7, 1], [7, 1, 7], [1, 7, 1], [7, 1, 7], and [1, 7, 1]

Examples

countBoomerangs([9, 5, 9, 5, 1, 1, 1]) ➞ 2

countBoomerangs([5, 6, 6, 7, 6, 3, 9]) ➞ 1

countBoomerangs([4, 4, 4, 9, 9, 9, 9]) ➞ 0

Notes

[5, 5, 5] (triple identical digits) is NOT considered a boomerang because the middle digit is identical to the first and last.

Solution:

1
2
3
4
5
6
7
8
9
function countBoomerangs(arr) {
	let sol = 0;
	for(let i = 2; i<arr.length; i++){
		if(arr[i] == arr[i-2] && arr[i]!==arr[i-1]){
			sol++;
		}
	}
	return sol;
}

Pluralize! [Edabit]

Given a list of words in the singular form, return a set of those words in the plural form if they appear more than once in the list.

Examples

pluralize(["cow", "pig", "cow", "cow"]) ➞ ["cows", "pig"]

pluralize(["table", "table", "table"]) ➞ ["tables"]

pluralize(["chair", "pencil", "arm"]) ➞ ["chair", "pencil", "arm"]

Notes

  • This is an oversimplification of the English language so no edge cases will appear.
  • Only focus on whether or not to add an s to the ends of words.
  • All tests will be valid.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function pluralize(arr) {
	let obj = {}
	for(let item of arr){
		if(obj[item]){
			obj[item]+=1;
		}else{
			obj[item] = 1;
		}
	}
	return Object.keys(obj).map(key=> obj[key] >1?`${key}s`:key)
}
	

Double Character Swap [Edabit]

Write a function to replace all instances of character c1 with character c2 and vice versa.

Examples

doubleSwap( "aabbccc", "a", "b") ➞ "bbaaccc"

doubleSwap("random w#rds writt&n h&r&", "#", "&")
➞ "random w&rds writt#n h#r#"

doubleSwap("128 895 556 788 999", "8", "9")
➞ "129 985 556 799 888"

Notes

Both characters will show up at least once in the string.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function doubleSwap(str, c1, c2) {
	let sol = "";
	for(let i = 0; i<str.length; i++){
		if(str[i] === c1){
			sol += c2;
		}else if(str[i] === c2){
			sol += c1;
		}else{
			sol += str[i];
		}
	}
	return sol;
}

Pandigital Numbers [Edabit]

pandigital number contains all digits (0-9) at least once. Write a function that takes an integer, returning true if the integer is pandigital, and false otherwise.

Examples

isPandigital(98140723568910) ➞ true

isPandigital(90864523148909) ➞ false
// 7 is missing.

isPandigital(112233445566778899) ➞ false

Notes

Think about the properties of a pandigital number when all duplicates are removed.

Solution:

1
2
3
4
function isPandigital(num) {
	let numStr = num.toString();
	return (new Set(numStr.split(""))).size == 10;
}