text
stringlengths
37
1.41M
''' There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-base...
''' Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character...
''' A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not. Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they ...
''' You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure : let x be the sum of all elements currently in your array. choose index i, such that 0 <= i < n and set the value of arr at index i to x. You may repeat this procedure as many times ...
''' You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left). If the current direction is right, move to the right child of the current node; otherwise, move to the left child. Change the direction from right to l...
''' You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the bal...
''' Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # ...
''' You are controlling a robot that is located somewhere in a room. The room is modeled as an m x n binary grid where 0 represents a wall and 1 represents an empty slot. The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the rob...
''' You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be changed to afte...
''' You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell. You are given an m x n character matrix, grid, of these different types of cells: '*' is your location. There is exactly one '*' cell. '#' is a food cell. There may be multiple food cel...
''' You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties: items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item. The value of each item in items is unique. Return a 2D integer ar...
''' Given an array of integers arr, sort the array by performing a series of pancake flips. In one pancake flip we do the following steps: Choose an integer k where 1 <= k <= arr.length. Reverse the sub-array arr[0...k-1] (0-indexed). For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we ...
''' Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans. ''' #my solution class Solution: def f(self, nums): r...
''' You are given a 0-indexed integer array candies, where candies[i] represents the flavor of the ith candy. Your mom wants you to share these candies with your little sister by giving her k consecutive candies, but you want to keep as many flavors of candies as possible. Return the maximum number of unique flavors o...
''' You are given a 0-indexed integer array nums of length n. The sum score of nums at an index i where 0 <= i < n is the maximum of: The sum of the first i + 1 elements of nums. The sum of the last n - i elements of nums. Return the maximum sum score of nums at any index. ''' class Solution: def maximumSumSc...
''' Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name ...
''' There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [hom...
''' Given two integers a and b, return any string s such that: s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters, The substring 'aaa' does not occur in s, and The substring 'bbb' does not occur in s. ''' class Solution: def strWithout3a3b(self, A: int, B: int) -> str: output...
''' Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. ''' #my own solution: class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: evens...
''' Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n. Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y...
''' Given the root of a binary tree, return the number of uni-value subtrees. A uni-value subtree means all nodes of the subtree have the same value. ''' def countUnivalSubtrees(self, root): self.count = 0 self.checkUni(root) return self.count # bottom-up, first check the leaf nodes and count them, # th...
''' You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal. Return true if it is possible to remove one letter so that the frequency of all letters in word ...
''' You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. You are also given an integer array queries....
''' The profiler will execute your code by executing the command python main.py. This problem does not require any input data, we will run your code once to determine whether the printed result is a multiplication table. When printing, print the multiplication in the order of increasing Multiplier, Print the mult...
''' Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is th...
''' You are given a list of integers rooms and an integer target. Return the first integer in rooms that's target or larger. If there is no solution, return -1. ''' class Solution: def solve(self, rooms, target): for i in range(len(rooms)): if rooms[i] >=target: ret...
''' You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d. Return the maximum number of events you can attend. ''' class Solu...
''' You are given an m x n 0-indexed 2D array of positive integers heights where heights[i][j] is the height of the person standing at position (i, j). A person standing at position (row1, col1) can see a person standing at position (row2, col2) if: The person at (row2, col2) is to the right or below the person at (r...
''' Given an array of prices [p1,p2...,pn] and a target, round each price pi to Roundi(pi) so that the rounded array [Round1(p1),Round2(p2)...,Roundn(pn)] sums to the given target. Each operation Roundi(pi) could be either Floor(pi) or Ceil(pi). Return the string "-1" if the rounded array is impossible to sum to ta...
''' Given a lowercase alphabet string s, return the index of the first recurring character in it. If there are no recurring characters, return -1. ''' class Solution: def solve(self, s): if len(s) <=1: return -1 d = dict() for i in range(len(s)): if s[i] not...
''' You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki]. The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi mus...
''' You are given a 0-indexed integer array nums. A pair of indices i, j where 0 <= i < j < nums.length is called beautiful if the first digit of nums[i] and the last digit of nums[j] are coprime. Return the total number of beautiful pairs in nums. Two integers x and y are coprime if there is no integer greater than ...
''' You are playing a Flip Game with your friend. You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner. Return all possible s...
''' Your code needs to read data n, m and n parameters from the standard input stream (console) in the form of A B C D. You need to calculate a matrix of n * m, the matrix element calculation formula is M[i][j]= \begin{cases} C[i]& \text{j = 0}\\ (A[i] * M[i][j - 1] + B[i]) \ \%\ D[i] & \text{j != 0} \end{cases}M[i][j...
''' You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: 0 <= i <= nums.length - 2,...
''' There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi. You will start on the 1st day and you cannot take two or more c...
''' Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules: The cost of painting a digit (i + 1) is given by cost[i] (0-indexed). The total cost used must be equal to target. The integer does not have 0 digits. Since the answer may be very large, retur...
''' There is a special keyboard with all keys in a single row. Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25). Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your f...
''' На вход подается строка str. Необходимо написать функцию magic_dict, которая будет составлять словарь, в котором ключами будут уникальные символы из str, а значениями - количество вхождений этих символов в строку str. При этом расположены элементы словаря должны быть в порядке лексикографического возрастания клю...
''' Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. ''' class Solution: def search(self, nums: List[int], target: int) -> int: low = 0 high = len(nums)...
''' Given an array of strings words, return true if it forms a valid word square. A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns). ''' class Solution: def validWordSquare(self, words: List[str]) -> bool: # Iterate each r...
''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. ''' #gives TLE error import math def f(nums): local_sum = 0 global_sum = float('-inf') print(nums) res = [] f...
''' A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city. You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in ...
''' Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of it...
''' You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values. We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then c...
''' A wonderful string is a string where at most one letter appears an odd number of times. For example, "ccjjc" and "abab" are wonderful, but "ab" is not. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the...
''' You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length. Return the number of steps performed until nums becomes a non-decreasing array. ''' class Solution(object): def totalSteps(self, nums): """ :type nums...
#Given a singly linked list, group all odd nodes together followed by the even nodes. #Please note here we are talking about the node number and not the value in the nodes # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next =...
''' You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer. The second greater integer of nums[i] is nums[j] such that: j > i nums[j] > nums[i] There exists exactly one index k such that nums[k] > nums[i] and i < k < j. If there is ...
''' Given two arrays nums1 and nums2. Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the...
''' Given a positive integer num, return the sum of its digits. Bonus: Can you do it without using strings? ''' class Solution: def solve(self, num): total = 0 while num: total += num%10 num = num//10 print(total) return total
''' Given a csv file path path, you are asked to read the contents of the csv file, then change 'name' in the first line to 'student_name', and then write the modified contents back to path. ''' import csv def get_write_csv(path:str): with open(path, 'r')as f: lines = f.readlines() lines[0] =...
''' You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them to...
''' Given a list of integer nums, return the earliest index i such that the sum of the numbers left of i is equal to the sum of numbers right of i. If there's no solution, return -1. Sum of an empty list is defined to be 0. ''' class Solution: def solve(self, nums): r = sum(nums) l = 0 for...
''' A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both a...
''' You are given two integers n and maxValue, which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Every arr[i] is a value from 1 to maxValue, for 0 <= i < n. Every arr[i] is divisible by arr[i - 1], for 0 < i < n. Return the numbe...
''' Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). ''' class Solution: def checkPossibility(self, nums: List[int]) ...
''' This question is about implementing a basic elimination algorithm for Candy Crush. Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy. A value of board[i][j] == 0 represents that the cell is empty. The given board represents the state of the game follo...
class Answer: def selection_sort(self, nums): def selectionSort(array, size): for ind in range(size): min_index = ind for j in range(ind + 1, size): # select the minimum element in every iteration if array[j] < array[min...
''' You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Add a positive integer to an element of a given index in the array nums2. Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 <= i < nums1.length and...
''' You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You...
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". ''' #my own solution class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: words = strs if len(words) == 1: return words[0...
''' There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id. Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The conc...
''' There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the ...
''' You are given an integer n representing the number of playing cards you have. A house of cards meets the following conditions: A house of cards consists of one or more rows of triangles and horizontal cards. Triangles are created by leaning two cards against each other. One card must be placed horizontally between...
''' Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: F1 = 1 F2 = 1 Fn = Fn-1 + Fn-2 for n > 2. It is guaranteed that for the given constraints we can always find such Fibonacci number...
''' You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0. In one operation: choose an index i such that 0 <= i < nums.length, increase your score by nums[i], and replace nums[i] with ceil(nums[i] / 3). Return the maximum possible score you can attain after applying exactly k o...
''' You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1. You are also given a strin...
''' Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. ''' class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 l = 0 r = len(height)-1 ...
''' Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'. ''' class Solution: def maxVowels(self, s: str, k: int) -> int: vowels = ["a","e","i","o","u"] #start ...
''' You are given a 0-indexed integer array nums and an integer k. Your task is to perform the following operation exactly k times in order to maximize your score: Select an element m from nums. Remove the selected element m from the array. Add a new element with a value of m + 1 to the array. Increase your score by m...
''' You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times: Operation 1: If the number contains the substring "00", you can replace it with "10". For example, "00010" -> "10010" Operation 2: If the number contains the substring "10", you c...
''' Implement a hash table with the following methods: HashTable() constructs a new instance of a hash table put(int key, int val) updates the hash table such that key maps to val get(int key) returns the value associated with key. If there is no such key, then return -1. remove(int key) removes both the key and the v...
''' A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present ...
''' Given a string s, return the maximum number of ocurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. ''' def maxFreq(self, s: str, maxLetters: int, minSize:...
''' You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times: Choose any piles[i] and remove floor(piles[i] / 2) stones from it. Notice that you can apply the operation on the same pile more...
''' You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0. You may assume that you ha...
''' In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0]. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return the minimum number of steps needed to ...
''' You are given a 0-indexed array words containing n strings. Let's define a join operation join(x, y) between two strings x and y as concatenating them into xy. However, if the last character of x is equal to the first character of y, one of them is deleted. For example join("ab", "ba") = "aba" and join("ab", "cde...
''' An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz". For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not. Given a string s consisting of lowercase letters on...
''' You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i]. For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied c...
''' There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). A team is valid if: (rating[i] < rating[j] < rating[k]) or (r...
''' Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1. ''' class Solution: def maximumDifference(self, nums: List[in...
''' Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, i...
''' You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers. Return a...
''' There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree. A subtree is a subset of cities where every city is ...
''' Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: Find the leftmost occurrence of the substring part and remove it from s. Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string. ''' ...
''' Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs. A pair (i, j) is fair if: 0 <= i < j < n, and lower <= nums[i] + nums[j] <= upper ''' class Solution: def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: def countL...
''' You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). Every worker ca...
''' A square matrix is said to be an X-Matrix if both of the following conditions hold: All the elements in the diagonals of the matrix are non-zero. All other elements are 0. Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false. ''' cla...
''' You are given a 0-indexed string street. Each character in street is either 'H' representing a house or '.' representing an empty space. You can place buckets on the empty spaces to collect rainwater that falls from the adjacent houses. The rainwater from a house at index i is collected if a bucket is placed at in...
''' You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for eac...
''' Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. ''' We can use 5 bits to represent the parity of the number of occurrences of vowels. For example, we can use 0/1 for even/odd number...
''' You are given two positive integer arrays nums1 and nums2, both of length n. The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute s...
''' from exponential program - kazak devs - Elzhan Zeinulla, 22 oct 2022 convert number to int. the number has commas separating every 3 digits: 1,700 = 1700 1,900,456 = 1900456 1 bln = 1000000000 1 trln = 1000000000000 ''' def f(s): s = s.split(',') temp = 0 pow = 0 s = s[::-1] # O(n) for ...
''' Given a string s, determine if it is valid. A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times: Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright....
''' Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next #horrible solution class Solution: def isPalindrome(se...
''' There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi. The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is ...
''' Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i...
''' You are given an integer n. There are n rooms numbered from 0 to n - 1. You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique. Meetings are allocated to rooms in the fo...