1374. Generate a String With Characters That Have Odd Counts [Leetcode]

Leetcode

Given an integer nreturn a string with n characters such that each character in such string occurs an odd number of times.

The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.  

Example 1:

Input: n = 4
Output: "pppz"
Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".

Example 2:

Input: n = 2
Output: "xy"
Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".

Example 3:

Input: n = 7
Output: "holasss"

Constraints:

  • 1 <= n <= 500

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/submissions/
 * @param {number} n
 * @return {string}
 */
var generateTheString = function (n) {
  if (n % 2 === 0) {
    return "a".repeat(n - 1) + "b";
  } else {
    return "a".repeat(n);
  }
};

557. Reverse Words in a String III [Leetcode]

Leetcode

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/reverse-words-in-a-string-iii/
 * @param {string} s
 * @return {string}
 */
var reverseWords = function (s) {
  let sol = s.split(" ").map((word) => {
    let rev = word.split("");
    for (let i = 0, j = word.length - 1; i < j; i++, j--) {
      let temp = rev[i];
      rev[i] = rev[j];
      rev[j] = temp;
    }
    return rev.join("");
  });
  return sol.join(" ");
};

1704. Determine if String Halves Are Alike [Leetcode]

Leetcode

You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels ('a''e''i''o''u''A''E''I''O''U'). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false.

Example 1:

Input: s = "book"
Output: true
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.

Example 2:

Input: s = "textbook"
Output: false
Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.

Example 3:

Input: s = "MerryChristmas"
Output: false

Example 4:

Input: s = "AbCdEfGh"
Output: true

Constraints:

  • 2 <= s.length <= 1000
  • s.length is even.
  • s consists of uppercase and lowercase letters.

Solution:

/**
 * https://leetcode.com/problems/determine-if-string-halves-are-alike/
 * github: theketan2
 * @param {string} s
 * @return {boolean}
 */
var halvesAreAlike = function (s) {
  let len = s.length / 2;
  let [w1, w2] = [s.substr(0, len), s.substr(len)];
  return (
    w1.toLowerCase().replace(/[^aeiou]/g, "").length ===
    w2.toLowerCase().replace(/[^aeiou]/g, "").length
  );
};

HTTP Requests [Edabit]

Edabit

Published by yanni in PythonLANGUAGESNo translations.Translatecompletestrings

The requests module is an HTTP library. You will be using it here to retrieve movie titles from the imdb.com website. See Resources for more details, but all you need for this challenge is get() and .text. The movie title can be easily located in the text of the web page because it is preceded by the HTML tag: <title> and followed by the tag: </title>.

The requests module is not a standard module but it can be accessed from the Edabit code editor. Improvise a function that takes an imdb.com address and returns the title of the movie at that address.

Examples

movie_title("https://www.imdb.com/title/tt0111161/") ➞ "The Shawshank Redemption (1994) - IMDb"

movie_title("https://www.imdb.com/title/tt0108052/") ➞ "Schindler"s List (1993) - IMDb"

movie_title("https://www.imdb.com/title/tt0073486/") ➞ "One Flew Over the Cuckoo"s Nest (1975) - IMDb"

Solution:

import requests
def movie_title(url):
	body = requests.get(url).text
	return body[body.index("<title>")+7: body.index("</title>")]
	

1450. Number of Students Doing Homework at a Given Time [Leetcode]

Leetcode

Given two integer arrays startTime and endTime and given an integer queryTime.

The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].

Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.

Example 1:

Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4
Output: 1
Explanation: We have 3 students where:
The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.
The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.
The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.

Example 2:

Input: startTime = [4], endTime = [4], queryTime = 4
Output: 1
Explanation: The only student was doing their homework at the queryTime.

Example 3:

Input: startTime = [4], endTime = [4], queryTime = 5
Output: 0

Example 4:

Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7
Output: 0

Example 5:

Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5
Output: 5

Constraints:

  • startTime.length == endTime.length
  • 1 <= startTime.length <= 100
  • 1 <= startTime[i] <= endTime[i] <= 1000
  • 1 <= queryTime <= 1000

Solution:

/**
 * https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time
 * github: theketan2
 * @param {number[]} startTime
 * @param {number[]} endTime
 * @param {number} queryTime
 * @return {number}
 */
var busyStudent = function (startTime, endTime, queryTime) {
  let sol = 0;
  for (let i = 0; i < startTime.length; i++) {
    if (startTime[i] <= queryTime && endTime[i] >= queryTime) {
      sol++;
    }
  }
  return sol;
};

1464. Maximum Product of Two Elements in an Array [Leetcode]

Leetcode

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of(nums[i]-1)*(nums[j]-1).

Example 1:

Input: nums = [3,4,5,2]
Output: 12 
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 

Example 2:

Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

Input: nums = [3,7]
Output: 12

Constraints:

  • 2 <= nums.length <= 500
  • 1 <= nums[i] <= 10^3

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function (nums) {
  nums.sort((a, b) => a - b);
  console.log(nums);
  let len = nums.length - 1;
  return (nums[len] - 1) * (nums[len - 1] - 1);
};

1588. Sum of All Odd Length Subarrays [Leetcode]

Leetcode

Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.

A subarray is a contiguous subsequence of the array.

Return the sum of all odd-length subarrays of arr.

Example 1:

Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

Example 2:

Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.

Example 3:

Input: arr = [10,11,12]
Output: 66

Constraints:

  • 1 <= arr.length <= 100
  • 1 <= arr[i] <= 1000

Solution:

/**
 * github: theketan2
 * https://leetcode.com/problems/sum-of-all-odd-length-subarrays/
 * @param {number[]} arr
 * @return {number}
 */
var sumOddLengthSubarrays = function (arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i += 2) {
    for (let j = 0; j < arr.length - i; j++) {
      sum += arr.slice(j, j + i + 1).reduce((acc, curr) => acc + curr);
      console.log(arr.slice(j, j + i + 1));
    }
  }
  return sum;
};

1688. Count of Matches in Tournament [Leetcode]

Leetcode

You are given an integer n, the number of teams in a tournament that has strange rules:

  • If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.
  • If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.

Return the number of matches played in the tournament until a winner is decided.

Example 1:

Input: n = 7
Output: 6
Explanation: Details of the tournament: 
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.

Example 2:

Input: n = 14
Output: 13
Explanation: Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.

Constraints:

  • 1 <= n <= 200

Solution:

/**
 * https://leetcode.com/problems/count-of-matches-in-tournament/
 * github: theketan2
 * @param {number} n
 * @return {number}
 */
var numberOfMatches = function (n) {
  let matches = 0;
  let reminder = 0;
  while (n) {
    n += reminder;
    reminder = n % 2;

    if (reminder) {
      n = (n - 1) / 2;
    } else {
      n /= 2;
    }
    matches += n;
  }
  return matches;
};

The Longest Substring [Edabit]

Edabit

Given a string of letters, create a function that returns a list with the separator that yields the longest possible substring, provided that:

  • The substring starts and ends with the separator.
  • The separator doesn’t occur inside the substring other than at the ends.

If two or more separators yield substrings with the same length, they should appear in alphabetical order.

Examples

max_separator("supercalifragilistic") ➞ ["s"]
# The longest substring is "supercalifragilis".

max_separator("laboratory") ➞ ["a", "o", "r"]
# "abora", "orato" and "rator" are the same length.

max_separator("candle") ➞ []
# No possible substrings.

Notes

  • All substrings should be at least of length 2 (i.e. no single-letter substrings).
  • Expect lowercase alphabetic characters only.

Solution:

def max_separator(txt):
	sol = []
	mx = 0
	for i in range(0, len(txt)):
		start = txt[i:].find(txt[i])
		end = txt[i+1:].find(txt[i])
		dist = end - start +1
		print(dist)
		if mx < dist:
			mx = dist
			sol = []
			sol.append(txt[i])
		elif mx == dist:
			sol.append(txt[i])
			
	return [] if len(sol) == len(txt) else sorted(sol)
	

1507. Reformat Date [Leetcode]

Leetcode

Given a date string in the form Day Month Year, where:

  • Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
  • Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
  • Year is in the range [1900, 2100].

Convert the date string to the format YYYY-MM-DD, where:

  • YYYY denotes the 4 digit year.
  • MM denotes the 2 digit month.
  • DD denotes the 2 digit day.

Example 1:

Input: date = "20th Oct 2052"
Output: "2052-10-20"

Example 2:

Input: date = "6th Jun 1933"
Output: "1933-06-06"

Example 3:

Input: date = "26th May 1960"
Output: "1960-05-26"

Solution:

/**
 * https://leetcode.com/problems/reformat-date/
 * github: theketan2
 * @param {string} date
 * @return {string}
 */
var reformatDate = function (date) {
  let months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
  ];
  let [day, month, year] = date.split(" ");
  return (
    year +
    "-" +
    ("00" + (months.indexOf(month) + 1)).substr(-2) +
    "-" +
    ("0" + parseInt(day)).substr(-2)
  );
};