647. Palindromic Substrings [Leetcode]

Leetcode

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

  1. The input string length won’t exceed 1000.

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/palindromic-substrings/submissions/
 * @param {string} s
 * @return {number}
 */
var countSubstrings = function (s) {
  let sol = 0;
  for (let i = 0; i < s.length; i++) {
    for (let j = i + 1; j < s.length + 1; j++) {
      let temp = s.substr(i, j - i);
      if (isPalim(temp)) {
        sol++;
      }
    }
  }
  return sol;
};

const isPalim = (str) => {
  for (let i = 0, j = str.length - 1; i < j; i++, j--) {
    if (str[i] !== str[j]) {
      return false;
    }
  }
  return true;
};

Simplified Fractions[Edabit]

Edabit

Create a function that returns the simplified version of a fraction.

Examples

simplify("4/6") ➞ "2/3"

simplify("10/11") ➞ "10/11"

simplify("100/400") ➞ "1/4"

simplify("8/4") ➞ "2"

Solution:

# https://edabit.com/challenge/vQgmyjcjMoMu9YGGW
def simplify(txt):
	a, b = [int(i) for i in txt.split("/")]
	for i in range(2, max(a,b)):
		while a%i ==0 and b%i==0:
			a /=i
			b /=i
	return str(round(a)) if b==1 else str(round(a))+"/"+str(round(b))
		

541. Reverse String II [Leetcode]

Leetcode

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

Example 1:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Example 2:

Input: s = "abcd", k = 2
Output: "bacd"

Constraints:

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.
  • 1 <= k <= 104

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/reverse-string-ii/
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var reverseStr = function (s, k) {
  let sol = "";
  for (let i = 0; i < s.length; i += k) {
    if ((i / k) % 2 == 0) sol += [...s.substr(i, k)].reverse().join("");
    else sol += s.substr(i, k);
  }
  return sol;
};

What’s the Data Type? [Edabit]

Edabit

Create a function that returns the data type of a given variable. These are the seven data types this challenge will be testing for:

  • List
  • Dictionary
  • String
  • Integer
  • Float
  • Boolean
  • Date

Examples

data_type([1, 2, 3, 4]) ➞ "list"

data_type({'key': "value"}) ➞ "dictionary"

data_type("This is an example string.") ➞ "string"

data_type(datetime.date(2018,1,1)) ➞ "date"

Notes

Return the name of the data type as a lowercase string.

Solution:

# https://edabit.com/challenge/i5kcGmT7gFKkf3mTi
def data_type(value):
	sol = {"dict":"dictionary","list":"list", "str":"string","int":"integer","float":"float","datetime.date":"date" }
	return sol[str(type(value)).replace('<class ',"")[1:-2]]
	

1089. Duplicate Zeros [Leetcode]

Leetcode

Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written.

Do the above modifications to the input array in place, do not return anything from your function.

Example 1:

Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]

Note:

  1. 1 <= arr.length <= 10000
  2. 0 <= arr[i] <= 9

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/duplicate-zeros/submissions/
 * @param {number[]} arr
 * @return {void} Do not return anything, modify arr in-place instead.
 */
var duplicateZeros = function (arr) {
  let temp = [];
  for (let elem of arr) {
    if (elem === 0) {
      temp.push(0);
      temp.push(0);
    } else {
      temp.push(elem);
    }
  }
  for (let i = 0; i < arr.length; i++) {
    arr[i] = temp[i];
  }
};

219. Contains Duplicate II [Leetcode]

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • 0 <= k <= 105

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/contains-duplicate-ii/
 * @param {number[]} nums
 * @param {number} k
 * @return {boolean}
 */
var containsNearbyDuplicate = function (nums, k) {
  for (let i = 0; i < nums.length - 1; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] === nums[j] && j - i <= k) {
        return true;
      }
    }
  }
  return false;
};

941. Valid Mountain Array [Leetcode]

Leetcode

Given an array of integers arr, return true if and only if it is a valid mountain array.

Recall that arr is a mountain array if and only if:

  • arr.length >= 3
  • There exists some i with 0 < i < arr.length - 1 such that:
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Example 1:

Input: arr = [2,1]
Output: false

Example 2:

Input: arr = [3,5,5]
Output: false

Example 3:

Input: arr = [0,3,2,1]
Output: true

Constraints:

  • 1 <= arr.length <= 104
  • 0 <= arr[i] <= 104

Solution:

/**
 * https://leetcode.com/problems/valid-mountain-array/
 * github: theketan2
 * @param {number[]} arr
 * @return {boolean}
 */
var validMountainArray = function (arr) {
  if (arr.length < 3) {
    return false;
  }
  let peak = Math.max(...arr);
  let index = arr.indexOf(peak);
  if (peak == arr[arr.length - 1] || peak === arr[0]) {
    return false;
  }
  let arr1 = [...arr.slice(0, index + 1)];
  let arr2 = [...arr.slice(index)];
  for (let i = 1; i < arr1.length; i++) {
    if (arr1[i - 1] >= arr1[i]) {
      return false;
    }
  }

  for (let i = 1; i < arr2.length; i++) {
    if (arr2[i - 1] <= arr2[i]) {
      return false;
    }
  }

  return true;
};

500. Keyboard Row [Leetcode]

Leetcode

Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

  • the first row consists of the characters "qwertyuiop",
  • the second row consists of the characters "asdfghjkl", and
  • the third row consists of the characters "zxcvbnm".

Example 1:

Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]

Example 2:

Input: words = ["omk"]
Output: []

Example 3:

Input: words = ["adsdf","sfd"]
Output: ["adsdf","sfd"]

Constraints:

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] consists of English letters (both lowercase and uppercase). 

Solution:

https://leetcode.com/problems/keyboard-row/submissions//**
 * github: theketan2
 * https://leetcode.com/problems/keyboard-row/
 * @param {string[]} words
 * @return {string[]}
 */
var findWords = function (words) {
  let rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"];
  let sol = [];
  for (let row of rows) {
    for (let word of words) {
      let flag = true;
      for (let ch of [...word]) {
        if (!row.includes(ch.toLowerCase())) {
          flag = false;
          break;
        }
      }
      if (flag) sol.push(word);
    }
  }
  return sol;
};

RGB to Hex Color Converter [Edabit]

Create a function that converts color in RGB format to Hex format.

Examples

rgb_to_hex("rgb(0, 128, 192)") ➞ "#0080c0"

rgb_to_hex("rgb(45, 255, 192)") ➞ "#2dffc0"

rgb_to_hex("rgb(0, 0, 0)") ➞ "#000000"

Notes

The Hex format should be displayed in lowercase.

# https://edabit.com/challenge/QyKRBtaMDWofm5D3u
def rgb_to_hex(col):
	lst = col.replace("rgb","").replace("(","").replace(")","").split(",")
	sol = "#"
	for item in lst:
		string = ""
		if item.strip() == "0":
			string = "00"
		else:
			string = str(hex(int(item)))[2:]
		sol += string
	return sol
	

228. Summary Ranges [Leetcode]

https://leetcode.com/problems/summary-ranges/

You are given a sorted unique integer array nums.

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

"a->b" if a != b
"a" if a == b
 

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"
Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"
Example 3:

Input: nums = []
Output: []
Example 4:

Input: nums = [-1]
Output: ["-1"]
Example 5:

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

Constraints:

0 <= nums.length <= 20
-231 <= nums[i] <= 231 - 1
All the values of nums are unique.
nums is sorted in ascending order.

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/summary-ranges/
 * @param {number[]} nums
 * @return {string[]}
 */
var summaryRanges = (nums) => {
  if (nums.length === 1) {
    return [nums[0].toString()];
  }
  nums.push(null);
  let sol = [];
  let temp = [];
  for (let elem of nums) {
    if (!temp.length) {
      temp.push(elem);
    } else if (elem - temp[temp.length - 1] === 1) {
      temp.push(elem);
    } else {
      sol.push(
        temp.length === 1
          ? temp[0].toString()
          : `${temp[0]}->${temp[temp.length - 1]}`
      );
      temp = [elem];
    }
  }
  return sol;
};