1833. Maximum Ice Cream Bars [Leetcode]

Leetcode

It is a sweltering summer day, and a boy wants to buy some ice cream bars.

At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. 

Return the maximum number of ice cream bars the boy can buy with coins coins.

Note: The boy can buy the ice cream bars in any order.

Example 1:

Input: costs = [1,3,2,4,1], coins = 7
Output: 4
Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.

Example 2:

Input: costs = [10,6,8,7,7,8], coins = 5
Output: 0
Explanation: The boy cannot afford any of the ice cream bars.

Example 3:

Input: costs = [1,6,3,1,2,5], coins = 20
Output: 6
Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.

Constraints:

  • costs.length == n
  • 1 <= n <= 105
  • 1 <= costs[i] <= 105
  • 1 <= coins <= 108

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/**
 * github: theketan2
 * https://leetcode.com/problems/maximum-ice-cream-bars/submissions/
 * @param {number[]} costs
 * @param {number} coins
 * @return {number}
 */
var maxIceCream = function (costs, coins) {
  let sol = 0;
  costs.sort((a, b) => a - b);
  let i = 0;
  while (coins && i < costs.length) {
    coins -= costs[i];
    if (coins >= 0) {
      sol++;
    }
    i++;
  }
  return sol;
};

1313. Decompress Run-Length Encoded List [Leetcode]

Leetcode

We are given a list nums of integers representing a list compressed with run-length encoding.

Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0).  For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.

Return the decompressed list.

Example 1:

Input: nums = [1,2,3,4]
Output: [2,4,4,4]
Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
At the end the concatenation [2] + [4,4,4] is [2,4,4,4].

Example 2:

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

Constraints:

  • 2 <= nums.length <= 100
  • nums.length % 2 == 0
  • 1 <= nums[i] <= 100

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
/**
 * github: theketan2
 * https://leetcode.com/problems/decompress-run-length-encoded-list/
 * @param {number[]} nums
 * @return {number[]}
 */
var decompressRLElist = function (nums) {
  let sol = [];
  for (let i = 1; i < nums.length; i += 2) {
    let temp = Array.from({ length: nums[i - 1] }, () => nums[i]);
    sol = [...sol, ...temp];
  }
  return sol;
};

929. Unique Email Addresses [Leetcode] #100DaysOfCode #LeetCode

Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.

  • For example, in "alice@leetcode.com""alice" is the local name, and "leetcode.com" is the domain name.

If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.

  • For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address.

If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.

  • For example, "m.y+name@email.com" will be forwarded to "my@email.com".

It is possible to use both of these rules at the same time.

Given an array of strings emails where we send one email to each email[i], return the number of different addresses that actually receive mails.

Example 1:

Input: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
Output: 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails.

Example 2:

Input: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"]
Output: 3

Constraints:

  • 1 <= emails.length <= 100
  • 1 <= emails[i].length <= 100
  • email[i] consist of lowercase English letters, '+''.' and '@'.
  • Each emails[i] contains exactly one '@' character.
  • All local and domain names are non-empty.
  • Local names do not start with a '+' character.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * github: theketan2
 * https://leetcode.com/problems/unique-email-addresses/
 * @param {string[]} emails
 * @return {number}
 */
var numUniqueEmails = function (emails) {
  let set = new Set();
  for (let str of emails) {
    let localName = str.slice(0, str.indexOf("@"));
    localName = localName.replace(/["."]/gi, "");
    localName = localName.includes("+")
      ? localName.slice(0, localName.indexOf("+"))
      : localName;
    // console.log(localName+str.slice(str.indexOf("@")))
    set.add(localName + str.slice(str.indexOf("@")));
  }
  return set.size;
};

1290. Convert Binary Number in a Linked List to Integer [Leetcode]

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

Return the decimal value of the number in the linked list.

Example 1:

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

Example 2:

Input: head = [0]
Output: 0

Example 3:

Input: head = [1]
Output: 1

Example 4:

Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
Output: 18880

Example 5:

Input: head = [0,0]
Output: 0

Constraints:

  • The Linked List is not empty.
  • Number of nodes will not exceed 30.
  • Each node’s value is either 0 or 1.

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/submissions/
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {number}
 */
var getDecimalValue = function (head) {
  let str = "";
  while (head.next !== null) {
    str += head.val;
    head = head.next;
  }
  str += head.val;
  // console.log(parseInt(str,2))
  return parseInt(str, 2);
};

1822. Sign of the Product of an Array [Leetcode]

There is a function signFunc(x) that returns:

  • 1 if x is positive.
  • -1 if x is negative.
  • 0 if x is equal to 0.

You are given an integer array nums. Let product be the product of all values in the array nums.

Return signFunc(product).

Example 1:

Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1

Example 2:

Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0

Example 3:

Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1

Constraints:

  • 1 <= nums.length <= 1000
  • -100 <= nums[i] <= 100

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/sign-of-the-product-of-an-array/submissions/
 * @param {number[]} nums
 * @return {number}
 */
var arraySign = function (nums) {
  let sum = nums.reduce((acc, curr) => acc * curr, 1);
  console.log(sum);
  return sum < 0 ? -1 : sum > 0 ? 1 : 0;
};

Check if the Sentence Is Pangram [Leetcode]

pangram is a sentence where every letter of the English alphabet appears at least once.

Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.

Example 1:

Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.

Example 2:

Input: sentence = "leetcode"
Output: false

Constraints:

  • 1 <= sentence.length <= 1000
  • sentence consists of lowercase English letters

/**
 * github: theketan2
 * https://leetcode.com/problems/check-if-the-sentence-is-pangram/submissions/
 * @param {string} sentence
 * @return {boolean}
 */
var checkIfPangram = function (sentence) {
  let alpha = "abcdefghijklmnopqrstuvwxyz";
  for (let char of [...alpha]) {
    if (!sentence.includes(char)) {
      return false;
    }
  }
  return true;
};

Intersection of Two Arrays II[Leetcode]

Leetcode

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Solution:

/**
 * github: theketan2
 * https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/674/
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersect = function (nums1, nums2) {
  let sol = [];
  for (let i = 0; i < nums2.length; i++) {
    let index = nums1.indexOf(nums2[i]);
    if (index >= 0) {
      sol.push(nums2[i]);
      nums1.splice(index, 1);
    }
  }
  return sol.sort();
};

Check If N and Its Double Exist [Leetcode]

Leetcode

Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).

More formally check if there exists two indices i and j such that :

  • i != j
  • 0 <= i, j < arr.length
  • arr[i] == 2 * arr[j]

Example 1:

Input: arr = [10,2,5,3]
Output: true
Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5.

Example 2:

Input: arr = [7,1,14,11]
Output: true
Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7.

Example 3:

Input: arr = [3,1,7,11]
Output: false
Explanation: In this case does not exist N and M, such that N = 2 * M.

Constraints:

  • 2 <= arr.length <= 500
  • -10^3 <= arr[i] <= 10^3

Solution:

/**
 * github: theketan2
 * https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3250/
 * @param {number[]} arr
 * @return {boolean}
 */
var checkIfExist = function (arr) {
  for (let i = 0; i < arr.length; i++) {
    let temp = [...arr];
    temp.splice(i, 1);
    // console.log(temp);
    if (temp.includes(arr[i] + arr[i])) {
      console.log(arr[i]);
      return true;
    }
  }
  return false;
};

234. Palindrome Linked List [Leetcode]

Given the head of a singly linked list, return true if it is a palindrome.

Example 1:

Input: head = [1,2,2,1]
Output: true

Example 2:

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

Constraints:

  • The number of nodes in the list is in the range [1, 105].
  • 0 <= Node.val <= 9

Follow up: Could you do it in O(n) time and O(1) space?

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/palindrome-linked-list/submissions/
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function (head) {
  let sol = [];
  // console.log(head.val)
  while (head.next !== null) {
    sol.push(head.val);
    head = head.next;
  }
  sol.push(head.val);
  // console.log(sol)
  for (let i = 0, j = sol.length - 1; i < j; i++, j--) {
    if (sol[i] !== sol[j]) {
      return false;
    }
  }
  return true;
};

643. Maximum Average Subarray I [Leetcode]

Leetcode

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

Note:

  1. 1 <= k <= n <= 30,000.
  2. Elements of the given array will be in the range [-10,000, 10,000].

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/maximum-average-subarray-i
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findMaxAverage = function (nums, k) {
  nums.push(0);
  let sol = [];
  for (let i = 0; i < nums.length - 1; i++) {
    let sum = 0;
    for (let j = i; j + 1 < nums.length; j++) {
      sum += nums[j];
      if (j - i + 1 == k) {
        sol.push(sum / k);
      }
    }
  }
  return Math.max(...sol);
};