389. Find the Difference [Leetcode]

Leetcode

You are given two strings s and t.

String t is generated by random shuffling string s and then add one more letter at a random position.

Return the letter that was added to t.

Example 1:

Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.

Example 2:

Input: s = "", t = "y"
Output: "y"

Example 3:

Input: s = "a", t = "aa"
Output: "a"

Example 4:

Input: s = "ae", t = "aea"
Output: "a"

Constraints:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s and t consist of lower-case English letters.

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/find-the-difference
 * @param {string} s
 * @param {string} t
 * @return {character}
 */
var findTheDifference = function (s, t) {
  for (let ch of [...s]) {
    t = t.replace(ch, "");
  }
  return t;
};

1046. Last Stone Weight [Leetcode]

Leetcode

We have a collection of stones, each stone has a positive integer weight.

Each turn, we choose the two heaviest stones and smash them together.  Suppose the stones have weights x and y with x <= y.  The result of this smash is:

  • If x == y, both stones are totally destroyed;
  • If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

At the end, there is at most 1 stone left.  Return the weight of this stone (or 0 if there are no stones left.)

Example 1:

Input: [2,7,4,1,8,1]
Output: 1
Explanation: 
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.

Note:

  1. 1 <= stones.length <= 30
  2. 1 <= stones[i] <= 1000

Solution:

/**https://leetcode.com/problems/last-stone-weight
 * @param {number[]} stones
 * @return {number}
 */
var lastStoneWeight = function(stones) {
    stones.sort((a,b)=> b-a)
    while(stones.length>=2){
        stones = [stones[0]-stones[1], ...stones.slice(2)];
        stones.sort((a,b)=> b-a);
    }
    console.log(stones.filter(num => num!==0))
    let sol = stones.filter(num => num!==0)
    return sol.length?sol[0]:0;
};

1331. Rank Transform of an Array [Leetcode]

Leetcode

Given an array of integers arr, replace each element with its rank.

The rank represents how large the element is. The rank has the following rules:

  • Rank is an integer starting from 1.
  • The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
  • Rank should be as small as possible.

Example 1:

Input: arr = [40,10,20,30]
Output: [4,1,2,3]
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.

Example 2:

Input: arr = [100,100,100]
Output: [1,1,1]
Explanation: Same elements share the same rank.

Example 3:

Input: arr = [37,12,28,9,100,56,80,5,12]
Output: [5,3,4,2,8,6,7,1,3]

Constraints:

  • 0 <= arr.length <= 105
  • -109 <= arr[i] <= 109

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/rank-transform-of-an-array
 * @param {number[]} arr
 * @return {number[]}
 */
var arrayRankTransform = function (arr) {
  let copy = [...Array.from(new Set(arr))];
  copy.sort((a, b) => Number(a) - Number(b));
  return arr.map((num) => copy.indexOf(num) + 1);
};

1408. String Matching in an Array [Leetcode]

Leetcode

Given an array of string words. Return all strings in words which is substring of another word in any order. 

String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j].

Example 1:

Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.

Example 2:

Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".

Example 3:

Input: words = ["blue","green","bu"]
Output: []

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 30
  • words[i] contains only lowercase English letters.
  • It’s guaranteed that words[i] will be unique.

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/string-matching-in-an-array
 * @param {string[]} words
 * @return {string[]}
 */
var stringMatching = function (words) {
  let sol = [];
  words.sort((a, b) => a.length - b.length);
  for (let i = 0; i < words.length - 1; i++) {
    let filter = words.slice(i + 1).filter((word) => word.includes(words[i]));
    if (filter.length) {
      sol.push(words[i]);
    }
  }
  return sol;
};

Censor Words Longer Than Four Characters [Edabit]

Edabit

Create a function that takes a string and censors words over four characters with *.

Examples

censor("The code is fourty") ➞ "The code is ******"

censor("Two plus three is five") ➞ "Two plus ***** is five"

censor("aaaa aaaaa 1234 12345") ➞ "aaaa ***** 1234 *****"

Notes

  • Don’t censor words with exactly four characters.
  • If all words have four characters or less, return the original string.
  • The amount of * is the same as the length of the word.

Solution:

def censor(s):
	lst = []
	for word in s.split(" "):
		if len(word)>4:
			lst.append("*"* len(word))
		else:
			lst.append(word)
	return " ".join(lst)

1200. Minimum Absolute Difference [Leetcode]

Leetcode

Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. 

Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows

  • a, b are from arr
  • a < b
  • b - a equals to the minimum absolute difference of any two elements in arr

Example 1:

Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

Example 2:

Input: arr = [1,3,6,10,15]
Output: [[1,3]]

Example 3:

Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]

Constraints:

  • 2 <= arr.length <= 10^5
  • -10^6 <= arr[i] <= 10^6

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/minimum-absolute-difference/
 * @param {number[]} arr
 * @return {number[][]}
 */
var minimumAbsDifference = function (arr) {
  let sol = [];
  arr.sort((a, b) => Number(a) - Number(b));
  let min = 99999999;
  for (let i = 1; i < arr.length; i++) {
    min = Math.min(arr[i] - arr[i - 1], min);
  }
  console.log(min);

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] - arr[i - 1] === min) {
      sol.push([arr[i - 1], arr[i]]);
    }
  }

  return sol;
};

Geometry 1: Length of Line Segment [Edabit]

Edabit

Write a function that takes coordinates of two points on a two-dimensional plane and returns the length of the line segment connecting those two points.

Examples

line_length([15, 7], [22, 11]) ➞ 8.06

line_length([0, 0], [0, 0]) ➞ 0

line_length([0, 0], [1, 1]) ➞ 1.41

Solution:

import math
def line_length(dot1, dot2):
	sol = math.sqrt(math.pow(dot1[0]-dot2[0], 2) + math.pow(dot1[1]-dot2[1], 2))
	return round(sol,2)

First Recurrence Index [Edabit]

Edabit

Create a function that identifies the very first item that has recurred in the string argument passed. It returns the identified item with the index where it first appeared and the very next index where it resurfaced ⁠— entirely as an dictionary; or as an empty dictionary if the argument is either None, an empty string, or no recurring item exists.

Examples

recur_index("DXTDXTXDTXD") ➞ {"D": [0, 3]}
// D first appeared at index 0, resurfaced at index 3
// T appeared and resurfaced at indices 3 and 6 but D completed the cycle first

recur_index("YXZXYTUVXWV") ➞ {"X": [1, 3]}

recur_index("YZTTZMNERXE") ➞ {"T": [2, 3]}

recur_index("AREDCBSDERD") ➞ {"D": [3, 7]}

recur_index("") ➞ {}

recur_index(None) ➞ {}

Solution:

def recur_index(txt):
	dictionary = {}
	if type(txt) != type("sajja"):
		return {}
	if len(txt) == 0 or len(set(list(txt))) == len(txt):
		return {}
	for i in range(len(txt)):
		try:
			dictionary[txt[i]]
			return {txt[i]: dictionary[txt[i]] + [i]}
		except:
			dictionary[txt[i]] = [i]

Simon Says [Edabit]

Edabit

Simon asks you to perform operations on a list of numbers that only he tells you. You should ignore all other instructions given. Create a function which evaluates a list of commands (written in plain English) if the command begins with Simon says. Return the result as an integer.

Examples

simon_says([
  "Simon says add 4",
  "Simon says add 6",
  "Then add 5"
]) ➞ 10

simon_says([
  "Susan says add 10",
  "Simon says add 3",
  "Simon says multiply by 8"
]) ➞ 24

simon_says([
  "Firstly, add 4",
  "Simeon says subtract 100"
]) ➞ 0

Solution:

def simon_says(lst):
	tot = 0
	for i in lst:
		if i.count("Simon says") == 1:
			wordLst = i.split(" ")
			if wordLst[2] == "add":
				tot += int(wordLst[-1])
			elif wordLst[2] == "subtract":
				tot -= int(wordLst[-1])
			elif wordLst[2] == "multiply":
				tot *= int(wordLst[-1])
	return tot

1304. Find N Unique Integers Sum up to Zero [Leetcode]

Leetcode

Given an integer n, return any array containing n unique integers such that they add up to 0.

Example 1:

Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Example 2:

Input: n = 3
Output: [-1,0,1]

Example 3:

Input: n = 1
Output: [0]

Constraints:

  • 1 <= n <= 1000

Solution:

/**https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/
 * @param {number} n
 * @return {number[]}
 */
var sumZero = function(n) {
    let sol = []
    if(n%2){
        sol.push(0);
    }
    
    for(let i = 1; i<=n/2; i++){
        sol.push(i)
        sol.push(-i)
    }
        
    return sol;
};