abh - HTMLify profile

abh
501 Files
101798 Views
Latest files of /abh/lc
impl Solution {
pub fn num_identical_pairs(nums: Vec<i32>) -> i32 {
let mut count = 0;
for i in 0..nums.len(){
for j in i+1..nums.len(){
if (nums[i] == nums[j]){
count += 1;
}
pub fn num_identical_pairs(nums: Vec<i32>) -> i32 {
let mut count = 0;
for i in 0..nums.len(){
for j in i+1..nums.len(){
if (nums[i] == nums[j]){
count += 1;
}
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if not num: return True
return num % 10
def isSameAfterReversals(self, num: int) -> bool:
if not num: return True
return num % 10
impl Solution {
pub fn is_same_after_reversals(num: i32) -> bool {
if (num != 0){
return num % 10 != 0;
}
else{
return true;
}
pub fn is_same_after_reversals(num: i32) -> bool {
if (num != 0){
return num % 10 != 0;
}
else{
return true;
}
/**
* @param {number} num
* @return {boolean}
*/
var isSameAfterReversals = function(num) {
if (num)
return num % 10 != 0;
else
* @param {number} num
* @return {boolean}
*/
var isSameAfterReversals = function(num) {
if (num)
return num % 10 != 0;
else
SELECT name, population, area FROM world WHERE area >= 3000000 or population >= 25000000;
SELECT name FROM Customer WHERE referee_id != 2 OR referee_id IS NULL;
SELECT product_id FROM Products WHERE low_fats = 'Y' AND recyclable = 'Y';
SELECT tweet_id FROM Tweets WHERE CHAR_LENGTH(content) > 15;
SELECT DISTINCT author_id AS id FROM Views WHERE author_id = viewer_id ORDER BY author_id;
/**
* @param {string} val
* @return {Object}
*/
var expect = function(val) {
return {"toBe":
function (valu){
if (valu === val)
* @param {string} val
* @return {Object}
*/
var expect = function(val) {
return {"toBe":
function (valu){
if (valu === val)
/**
* @return {Function}
*/
var createHelloWorld = function() {
return function(...args) {
return "Hello World";
}
* @return {Function}
*/
var createHelloWorld = function() {
return function(...args) {
return "Hello World";
}
/**
* @param {number} n
* @return {Function} counter
*/
var createCounter = function(n) {
let count = n;
return function() {
return count++;
* @param {number} n
* @return {Function} counter
*/
var createCounter = function(n) {
let count = n;
return function() {
return count++;
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
return {
"init": init,
"count": init,
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
return {
"init": init,
"count": init,
/**
* @param {Function[]} functions
* @return {Function}
*/
var compose = function(functions) {
return function(x) {
functions.reverse();
* @param {Function[]} functions
* @return {Function}
*/
var compose = function(functions) {
return function(x) {
functions.reverse();
/**
* @param {...(null|boolean|number|string|Array|Object)} args
* @return {number}
*/
var argumentsLength = function(...args) {
return args.length;
};
* @param {...(null|boolean|number|string|Array|Object)} args
* @return {number}
*/
var argumentsLength = function(...args) {
return args.length;
};
/**
* @param {Function} fn
* @return {Function}
*/
var once = function(fn) {
let called = false;
return function(...args){
if (called)
* @param {Function} fn
* @return {Function}
*/
var once = function(fn) {
let called = false;
return function(...args){
if (called)
SELECT user_id, count(follower_id) as followers_count FROM Followers GROUP BY user_id ORDER BY user_id;
class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2
def sum(self, num1: int, num2: int) -> int:
return num1 + num2
/**
* @param {number} num1
* @param {number} num2
* @return {number}
*/
var sum = function(num1, num2) {
return num1 + num2;
};
* @param {number} num1
* @param {number} num2
* @return {number}
*/
var sum = function(num1, num2) {
return num1 + num2;
};
impl Solution {
pub fn sum(num1: i32, num2: i32) -> i32 {
return num1 + num2;
}
}
pub fn sum(num1: i32, num2: i32) -> i32 {
return num1 + num2;
}
}
# @param {Integer} num1
# @param {Integer} num2
# @return {Integer}
def sum(num1, num2)
return num1 + num2
end
# @param {Integer} num2
# @return {Integer}
def sum(num1, num2)
return num1 + num2
end
object Solution {
def sum(num1: Int, num2: Int): Int = {
return num1 + num2;
}
}
def sum(num1: Int, num2: Int): Int = {
return num1 + num2;
}
}
class Solution:
def fib(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
fibo = [0, 1]
for _ in range(n-1):
def fib(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
fibo = [0, 1]
for _ in range(n-1):
impl Solution {
pub fn fib(n: i32) -> i32 {
if (n == 0){
return 0;
}
if (n == 1){
return 1;
}
pub fn fib(n: i32) -> i32 {
if (n == 0){
return 0;
}
if (n == 1){
return 1;
}
/**
* @param {number} n
* @return {number}
*/
var fib = function(n) {
if (n == 0)
return 0;
if (n == 1)
* @param {number} n
* @return {number}
*/
var fib = function(n) {
if (n == 0)
return 0;
if (n == 1)
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
i = 0
s = 0
if len(mat)%2:
s -= mat[len(mat)//2][len(mat)//2]
for row in mat:
s += row[i] + row[len(mat)-i-1]
def diagonalSum(self, mat: List[List[int]]) -> int:
i = 0
s = 0
if len(mat)%2:
s -= mat[len(mat)//2][len(mat)//2]
for row in mat:
s += row[i] + row[len(mat)-i-1]
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
target = []
for n, i in zip(nums, index):
target.insert(i, n)
return target
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
target = []
for n, i in zip(nums, index):
target.insert(i, n)
return target
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
shuffeld = ""
for i in range(len(s)):
shuffeld += s[indices.index(i)]
return shuffeld
def restoreString(self, s: str, indices: List[int]) -> str:
shuffeld = ""
for i in range(len(s)):
shuffeld += s[indices.index(i)]
return shuffeld
/**
* @param {Array} arr
* @param {number} size
* @return {Array}
*/
var chunk = function(arr, size) {
const chunked = [];
let chunk = [];
* @param {Array} arr
* @param {number} size
* @return {Array}
*/
var chunk = function(arr, size) {
const chunked = [];
let chunk = [];
class Solution:
def separateDigits(self, nums: List[int]) -> List[int]:
saprated = []
for num in nums:
if isinstance(num, list):
saprated.append(Solution.separateDigits(num))
else:
digits = []
def separateDigits(self, nums: List[int]) -> List[int]:
saprated = []
for num in nums:
if isinstance(num, list):
saprated.append(Solution.separateDigits(num))
else:
digits = []
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
smallercount = []
sortednums = sorted(nums)
for n in nums:
smallercount.append(sortednums.index(n))
return smallercount
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
smallercount = []
sortednums = sorted(nums)
for n in nums:
smallercount.append(sortednums.index(n))
return smallercount
class Solution:
def findChampion(self, grid: List[List[int]]) -> int:
n = len(grid)
strongerthancount = [0]*n
for i in range(n):
for j in range(n):
if i != j:
strongerthancount[i] += grid[i][j]
def findChampion(self, grid: List[List[int]]) -> int:
n = len(grid)
strongerthancount = [0]*n
for i in range(n):
for j in range(n):
if i != j:
strongerthancount[i] += grid[i][j]
# Write your MySQL query statement below
SELECT * FROM patients
WHERE conditions LIKE '% DIAB1%' or conditions LIKE 'DIAB1%' ;
SELECT * FROM patients
WHERE conditions LIKE '% DIAB1%' or conditions LIKE 'DIAB1%' ;
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
s = list(s)
chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM"
letters = []
for c in s:
if c in chars:
letters.append(c)
def reverseOnlyLetters(self, s: str) -> str:
s = list(s)
chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM"
letters = []
for c in s:
if c in chars:
letters.append(c)
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
if target in row:
return True
return False
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
if target in row:
return True
return False
class Solution:
def repeatedCharacter(self, s: str) -> str:
seen = set()
for c in s:
if c in seen:
return c
seen.add(c)
def repeatedCharacter(self, s: str) -> str:
seen = set()
for c in s:
if c in seen:
return c
seen.add(c)
/**
* @param {string} s
* @return {character}
*/
var repeatedCharacter = function(s) {
seen = [];
for (let i=0;i<s.length;i++){
if (seen.includes(s[i]))
* @param {string} s
* @return {character}
*/
var repeatedCharacter = function(s) {
seen = [];
for (let i=0;i<s.length;i++){
if (seen.includes(s[i]))
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
count = 0
for c in s:
if not g:
break
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
count = 0
for c in s:
if not g:
break
class Solution:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
mat = []
for n in nums:
put = False
for row in mat:
if not n in row:
row.append(n)
def findMatrix(self, nums: List[int]) -> List[List[int]]:
mat = []
for n in nums:
put = False
for row in mat:
if not n in row:
row.append(n)
class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
beams = 0
pre_lesers = 0
for floor in bank:
if floor.count("1") == 0:
continue
beams += pre_lesers * floor.count("1")
def numberOfBeams(self, bank: List[str]) -> int:
beams = 0
pre_lesers = 0
for floor in bank:
if floor.count("1") == 0:
continue
beams += pre_lesers * floor.count("1")
public class Solution {
public int NumberOfBeams(string[] bank) {
int pre_lesers = 0;
int beams = 0;
foreach (string floor in bank){
int current_lesers = 0;
foreach (char c in floor){
if (c == '1')
public int NumberOfBeams(string[] bank) {
int pre_lesers = 0;
int beams = 0;
foreach (string floor in bank){
int current_lesers = 0;
foreach (char c in floor){
if (c == '1')
class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
secs = 0
while "01" in s:
s = s.replace("01", "10")
secs += 1
return secs
def secondsToRemoveOccurrences(self, s: str) -> int:
secs = 0
while "01" in s:
s = s.replace("01", "10")
secs += 1
return secs
class Solution:
def isGood(self, nums: List[int]) -> bool:
nums.sort()
good = list(range(1, len(nums))) + [len(nums)-1]
return nums == good
def isGood(self, nums: List[int]) -> bool:
nums.sort()
good = list(range(1, len(nums))) + [len(nums)-1]
return nums == good
from random import choice
class RandomizedSet:
def __init__(self):
self.values = []
def insert(self, val: int) -> bool:
if val in self.values:
class RandomizedSet:
def __init__(self):
self.values = []
def insert(self, val: int) -> bool:
if val in self.values:
from random import choice
class RandomizedCollection:
def __init__(self):
self.values = []
def insert(self, val: int) -> bool:
exist = not val in self.values
class RandomizedCollection:
def __init__(self):
self.values = []
def insert(self, val: int) -> bool:
exist = not val in self.values
class Solution:
def maximumOddBinaryNumber(self, s: str) -> str:
if s.count("1") == 1:
return ("0" * (len(s) - 1)) + "1"
return ("1" * (s.count("1")-1)) + ("0" * s.count("0")) + "1"
def maximumOddBinaryNumber(self, s: str) -> str:
if s.count("1") == 1:
return ("0" * (len(s) - 1)) + "1"
return ("1" * (s.count("1")-1)) + ("0" * s.count("0")) + "1"
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
return list(sorted(map(lambda a:a*a, nums)))
def sortedSquares(self, nums: List[int]) -> List[int]:
return list(sorted(map(lambda a:a*a, nums)))
class Solution:
def findMaxK(self, nums: List[int]) -> int:
nums.sort()
l = -1
for n in nums:
if n < 0:
continue
if -n in nums:
def findMaxK(self, nums: List[int]) -> int:
nums.sort()
l = -1
for n in nums:
if n < 0:
continue
if -n in nums:
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
s = nums1[:m].copy() + nums2.copy()
for i in range(m+n):
e = min(s)
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
s = nums1[:m].copy() + nums2.copy()
for i in range(m+n):
e = min(s)
class Solution:
def reverseVowels(self, s: str) -> str:
rvs = ""
for c in s[::-1]:
if c in "aeiouAEIOU":
rvs += c
ns = ""
p = 0
def reverseVowels(self, s: str) -> str:
rvs = ""
for c in s[::-1]:
if c in "aeiouAEIOU":
rvs += c
ns = ""
p = 0
class Solution:
def pickGifts(self, gifts: List[int], k: int) -> int:
for _ in range(k):
m = max(gifts)
gifts[gifts.index(m)] = int(m**(1/2))
return sum(gifts)
def pickGifts(self, gifts: List[int], k: int) -> int:
for _ in range(k):
m = max(gifts)
gifts[gifts.index(m)] = int(m**(1/2))
return sum(gifts)
class Solution:
def majorityElement(self, nums: List[int]) -> int:
f = int(len(nums)/2)
for n in set(nums):
if nums.count(n) > f:
return n
def majorityElement(self, nums: List[int]) -> int:
f = int(len(nums)/2)
for n in set(nums):
if nums.count(n) > f:
return n
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for word in sentence.split(" "):
if word.startswith(searchWord):
return sentence.split(" ").index(word) + 1
return -1
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for word in sentence.split(" "):
if word.startswith(searchWord):
return sentence.split(" ").index(word) + 1
return -1
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from random import randint
class Solution:
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from random import randint
class Solution:
from random import choice
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def pick(self, target: int) -> int:
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def pick(self, target: int) -> int:
class Solution:
def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:
for _ in range(k):
m = min(nums)
for i, n in enumerate(nums):
if n == m:
nums[i] *= multiplier
break
def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]:
for _ in range(k):
m = min(nums)
for i, n in enumerate(nums):
if n == m:
nums[i] *= multiplier
break
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
for _ in range(len(s)):
s = s[1:] + s[0]
print(s)
if s == goal:
return True
return False
def rotateString(self, s: str, goal: str) -> bool:
for _ in range(len(s)):
s = s[1:] + s[0]
print(s)
if s == goal:
return True
return False
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
galla = []
for bill in bills:
if bill == 5:
galla.append(5)
if bill == 10:
if 5 not in galla:
def lemonadeChange(self, bills: List[int]) -> bool:
galla = []
for bill in bills:
if bill == 5:
galla.append(5)
if bill == 10:
if 5 not in galla:
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
for i in range(len(prices)-1):
for j in range(i+1, len(prices)):
if prices[i] >= prices[j]:
prices[i] -= prices[j]
break
return prices
def finalPrices(self, prices: List[int]) -> List[int]:
for i in range(len(prices)-1):
for j in range(i+1, len(prices)):
if prices[i] >= prices[j]:
prices[i] -= prices[j]
break
return prices
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
for i in range(len(arr)):
for j in range(len(arr)):
if i == j:
continue
if arr[i] == arr[j] * 2:
return True
def checkIfExist(self, arr: List[int]) -> bool:
for i in range(len(arr)):
for j in range(len(arr)):
if i == j:
continue
if arr[i] == arr[j] * 2:
return True
class Solution:
def scoreOfString(self, s: str) -> int:
values = []
for c in s:
values.append(ord(c))
score = 0
for i in range(len(values)-1):
score += abs(values[i] - values[i+1])
def scoreOfString(self, s: str) -> int:
values = []
for c in s:
values.append(ord(c))
score = 0
for i in range(len(values)-1):
score += abs(values[i] - values[i+1])
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + (t*2)
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + (t*2)
class Solution:
def makeFancyString(self, s: str) -> str:
for c in set(s):
while c*3 in s:
s = s.replace(c*3, c*2)
return s
def makeFancyString(self, s: str) -> str:
for c in set(s):
while c*3 in s:
s = s.replace(c*3, c*2)
return s
class Solution:
def minLength(self, s: str) -> int:
while "AB" in s or "CD" in s:
s = s.replace("AB", "")
s = s.replace("CD", "")
return len(s)
def minLength(self, s: str) -> int:
while "AB" in s or "CD" in s:
s = s.replace("AB", "")
s = s.replace("CD", "")
return len(s)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def get_level(self, root, level: int) -> List[TreeNode]:
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def get_level(self, root, level: int) -> List[TreeNode]:
class Solution:
def countSeniors(self, details: List[str]) -> int:
return len(list(filter(lambda p: p>60, [int(p[11:-2]) for p in details])))
def countSeniors(self, details: List[str]) -> int:
return len(list(filter(lambda p: p>60, [int(p[11:-2]) for p in details])))
class Solution:
def getLucky(self, s: str, k: int) -> int:
n = ""
for c in s:
n += str(ord(c)-96)
for _ in range(k):
s = 0
for n_ in n:
def getLucky(self, s: str, k: int) -> int:
n = ""
for c in s:
n += str(ord(c)-96)
for _ in range(k):
s = 0
for n_ in n:
class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
fa = s.count(s[0])
for c in set(s):
if s.count(c) != fa:
return False
return True
def areOccurrencesEqual(self, s: str) -> bool:
fa = s.count(s[0])
for c in set(s):
if s.count(c) != fa:
return False
return True
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
sentence = sentence.split(" ")
if sentence[0][0] != sentence[-1][-1]:
return False
for i in range(len(sentence)-1):
if sentence[i][-1] != sentence[i+1][0]:
return False
def isCircularSentence(self, sentence: str) -> bool:
sentence = sentence.split(" ")
if sentence[0][0] != sentence[-1][-1]:
return False
for i in range(len(sentence)-1):
if sentence[i][-1] != sentence[i+1][0]:
return False
class Solution:
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
uncommon_words = []
s1 = s1.split()
s2 = s2.split()
for word in s1:
if s1.count(word) == 1 and word not in s2:
uncommon_words.append(word)
def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
uncommon_words = []
s1 = s1.split()
s2 = s2.split()
for word in s1:
if s1.count(word) == 1 and word not in s2:
uncommon_words.append(word)
class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
return sorted(target) == sorted(arr)
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
return sorted(target) == sorted(arr)
class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
return [names[heights.index(h)] for h in sorted(heights, reverse=True)]
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
return [names[heights.index(h)] for h in sorted(heights, reverse=True)]
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
distinct = []
for c in arr:
if arr.count(c) > 1:
continue
if c not in distinct:
distinct.append(c)
def kthDistinct(self, arr: List[str], k: int) -> str:
distinct = []
for c in arr:
if arr.count(c) > 1:
continue
if c not in distinct:
distinct.append(c)
class Solution:
def frequencySort(self, nums: List[int]) -> List[int]:
freq = []
for n in set(nums):
freq.append((n, nums.count(n)))
freq = sorted(freq, key=lambda e:e[1])
ans = []
f = 1
def frequencySort(self, nums: List[int]) -> List[int]:
freq = []
for n in set(nums):
freq.append((n, nums.count(n)))
freq = sorted(freq, key=lambda e:e[1])
ans = []
f = 1
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
return len(list(filter(lambda e:set(e)<=set(allowed),words)))
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
return len(list(filter(lambda e:set(e)<=set(allowed),words)))
class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
return sorted(nums, key=lambda e: int(bool(e)), reverse=True)
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
return sorted(nums, key=lambda e: int(bool(e)), reverse=True)
class Solution:
def findComplement(self, num: int) -> int:
b = bin(num)[2:]
b = b.replace("0", "2")
b = b.replace("1", "0")
b = b.replace("2", "1")
return int(b, 2)
def findComplement(self, num: int) -> int:
b = bin(num)[2:]
b = b.replace("0", "2")
b = b.replace("1", "0")
b = b.replace("2", "1")
return int(b, 2)
from random import shuffle
class Solution:
def __init__(self, nums: List[int]):
self.list = nums
self.orgi = nums.copy()
class Solution:
def __init__(self, nums: List[int]):
self.list = nums
self.orgi = nums.copy()
class Solution:
def minBitFlips(self, start: int, goal: int) -> int:
bb = len(bin(max([start, goal]))) - 2
sb = bin(start)[2:].zfill(bb)
gb = bin(goal)[2:].zfill(bb)
d = 0
for i in range(bb):
if sb[i] != gb[i]:
def minBitFlips(self, start: int, goal: int) -> int:
bb = len(bin(max([start, goal]))) - 2
sb = bin(start)[2:].zfill(bb)
gb = bin(goal)[2:].zfill(bb)
d = 0
for i in range(bb):
if sb[i] != gb[i]:
class Solution:
def maxScore(self, s: str) -> int:
maxscore = 0
for i in range(1, len(s)):
l = s[:i]
r = s[i:]
score = l.count("0") + r.count("1")
if score > maxscore:
def maxScore(self, s: str) -> int:
maxscore = 0
for i in range(1, len(s)):
l = s[:i]
r = s[i:]
score = l.count("0") + r.count("1")
if score > maxscore:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
pad = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
def letterCombinations(self, digits: str) -> List[str]:
pad = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
c = 0
ls = 0
rs = sum(nums)
for i in range(len(nums)-1):
n = nums[i]
ls += n
def waysToSplitArray(self, nums: List[int]) -> int:
c = 0
ls = 0
rs = sum(nums)
for i in range(len(nums)-1):
n = nums[i]
ls += n
class Solution:
def reformatDate(self, date: str) -> str:
days = [
"1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th",
"11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th",
"21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th",
"31st"
]
def reformatDate(self, date: str) -> str:
days = [
"1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th",
"11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th",
"21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th",
"31st"
]
class Solution:
def countSegments(self, s: str) -> int:
n = 0
f = True
for c in s+" ":
if c == " ":
if not f:
n += 1
def countSegments(self, s: str) -> int:
n = 0
f = True
for c in s+" ":
if c == " ":
if not f:
n += 1
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
l = sorted(map(lambda e:str(e), range(1, n+1)))
return int(l[k-1])
def findKthNumber(self, n: int, k: int) -> int:
l = sorted(map(lambda e:str(e), range(1, n+1)))
return int(l[k-1])
class Solution:
def sortSentence(self, s: str) -> str:
return " ".join([w[:-1] for w in sorted(s.split(), key=lambda e:int(e[-1]))])
def sortSentence(self, s: str) -> str:
return " ".join([w[:-1] for w in sorted(s.split(), key=lambda e:int(e[-1]))])
class Solution:
def convertDateToBinary(self, date: str) -> str:
return "-".join([bin(int(e))[2:] for e in date.split("-")])
def convertDateToBinary(self, date: str) -> str:
return "-".join([bin(int(e))[2:] for e in date.split("-")])
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
return [c + extraCandies >= max(candies) for c in candies]
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
return [c + extraCandies >= max(candies) for c in candies]
class Solution:
def isPrefixAndSuffix(self, str1: str, str2: str):
return str2.startswith(str1) and str2.endswith(str1)
def countPrefixSuffixPairs(self, words: List[str]) -> int:
c = 0
for i in range(len(words)):
for j in range(i+1, len(words)):
def isPrefixAndSuffix(self, str1: str, str2: str):
return str2.startswith(str1) and str2.endswith(str1)
def countPrefixSuffixPairs(self, words: List[str]) -> int:
c = 0
for i in range(len(words)):
for j in range(i+1, len(words)):
class Solution:
def isValid(self, s: str) -> bool:
stack = []
m = {
')': '(',
'}': '{',
']': '[',
}
def isValid(self, s: str) -> bool:
stack = []
m = {
')': '(',
'}': '{',
']': '[',
}
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.values = sorted(nums)
self.k = k
def add(self, val: int) -> int:
if not self.values:
def __init__(self, k: int, nums: List[int]):
self.values = sorted(nums)
self.k = k
def add(self, val: int) -> int:
if not self.values:
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
return len(list(filter(lambda e:e.startswith(pref), words)))
def prefixCount(self, words: List[str], pref: str) -> int:
return len(list(filter(lambda e:e.startswith(pref), words)))
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
return len(nums)
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
return len(nums)
class Solution:
def evenOddBit(self, n: int) -> List[int]:
ans = [0, 0]
for i, v in enumerate(bin(n)[2:][::-1]):
if v == "0":
continue
if i%2:
ans[1] += 1
def evenOddBit(self, n: int) -> List[int]:
ans = [0, 0]
for i, v in enumerate(bin(n)[2:][::-1]):
if v == "0":
continue
if i%2:
ans[1] += 1
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
n1 = 0
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
n1 = 0
class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
ans = []
for word in words:
for word_ in words:
if word == word_:
continue
if word in word_:
def stringMatching(self, words: List[str]) -> List[str]:
ans = []
for word in words:
for word_ in words:
if word == word_:
continue
if word in word_:
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if len(s) < k: return False
m = {}
oc = 0
for c in set(s):
m[c] = s.count(c)
oc += 1 if m[c]%2 else 0
def canConstruct(self, s: str, k: int) -> bool:
if len(s) < k: return False
m = {}
oc = 0
for c in set(s):
m[c] = s.count(c)
oc += 1 if m[c]%2 else 0
class Solution:
def validIPAddress(self, queryIP: str) -> str:
if "." in queryIP:
try:
if queryIP[0]=="0"or(".0"in queryIP and ".0." not in queryIP):
raise ValueError
ns = list(map(int, queryIP.split(".")))
if len(ns) != 4:
def validIPAddress(self, queryIP: str) -> str:
if "." in queryIP:
try:
if queryIP[0]=="0"or(".0"in queryIP and ".0." not in queryIP):
raise ValueError
ns = list(map(int, queryIP.split(".")))
if len(ns) != 4:
from time import sleep
class Foo:
def __init__(self):
self.last_print = 0
def first(self, printFirst: 'Callable[[], None]') -> None:
class Foo:
def __init__(self):
self.last_print = 0
def first(self, printFirst: 'Callable[[], None]') -> None:
from time import sleep
class FooBar:
def __init__(self, n):
self.n = n
self.next = "foo"
class FooBar:
def __init__(self, n):
self.n = n
self.next = "foo"
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
sl = ListNode(None)
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
sl = ListNode(None)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return sorted(nums, key=lambda e:nums.count(e))[0]
def singleNumber(self, nums: List[int]) -> int:
return sorted(nums, key=lambda e:nums.count(e))[0]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
#if not lists or not all(lists):
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
#if not lists or not all(lists):
class Solution:
def isPalindrome(self, s: str) -> bool:
fls = "".join([c for c in s.lower() if c in "pyfgcrlaoeuidhtnsqjkxbmwvz1234567890"])
return fls == fls[::-1]
def isPalindrome(self, s: str) -> bool:
fls = "".join([c for c in s.lower() if c in "pyfgcrlaoeuidhtnsqjkxbmwvz1234567890"])
return fls == fls[::-1]
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1: return [[nums[0]]]
combs = []
for n in nums:
tnums = nums.copy()
tnums.remove(n)
scombs = self.permute(tnums)
def permute(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1: return [[nums[0]]]
combs = []
for n in nums:
tnums = nums.copy()
tnums.remove(n)
scombs = self.permute(tnums)
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
for i in range(len(s)//2): s[i], s[len(s)-1-i] = s[len(s)-i-1], s[i]
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
for i in range(len(s)//2): s[i], s[len(s)-1-i] = s[len(s)-i-1], s[i]
func sumOfUnique(nums []int) int {
var sum int = 0;
for i := 0; i < len(nums); i++ {
var u bool = true
for j := 0; j < len(nums); j++ {
if i == j {
continue
} else {
var sum int = 0;
for i := 0; i < len(nums); i++ {
var u bool = true
for j := 0; j < len(nums); j++ {
if i == j {
continue
} else {
func int_to_binary(n int) string {
var b string = ""
for ;n!=0; {
if n % 2 == 0 {
b = "0" + b
} else {
b = "1" + b
}
var b string = ""
for ;n!=0; {
if n % 2 == 0 {
b = "0" + b
} else {
b = "1" + b
}
func findFinalValue(nums []int, original int) int {
for ;true; {
f := false
for _, n := range nums {
if n == original {
f = true
break
}
for ;true; {
f := false
for _, n := range nums {
if n == original {
f = true
break
}
func int_to_str(n int) string {
s := ""
if n < 0 {
s += "-"
n *= -1
}
for ;n!=0; {
m := n % 10
s := ""
if n < 0 {
s += "-"
n *= -1
}
for ;n!=0; {
m := n % 10
class Solution:
def reverse(self, x):
if x < 0: n = -1; x = x * (-1)
else: n = 1
r = 0
while x > 0:
r = (r * 10) + x % 10
x//=10
def reverse(self, x):
if x < 0: n = -1; x = x * (-1)
else: n = 1
r = 0
while x > 0:
r = (r * 10) + x % 10
x//=10
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
last_i = None
for i in range(0, len(numbers)-1):
if numbers[i] == last_i:
continue
for j in range(i+1, len(numbers)):
s = numbers[i] + numbers[j]
def twoSum(self, numbers: List[int], target: int) -> List[int]:
last_i = None
for i in range(0, len(numbers)-1):
if numbers[i] == last_i:
continue
for j in range(i+1, len(numbers)):
s = numbers[i] + numbers[j]
func twoSum(numbers []int, target int) []int {
var last_i int
for i:=0;i<len(numbers)-1;i++ {
if i!=0 && last_i == numbers[i] {
continue
}
for j:=i+1;j<len(numbers);j++ {
if numbers[i] + numbers[j] == target {
var last_i int
for i:=0;i<len(numbers)-1;i++ {
if i!=0 && last_i == numbers[i] {
continue
}
for j:=i+1;j<len(numbers);j++ {
if numbers[i] + numbers[j] == target {
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
func one_count(n int) int {
var count int
for ;n!=0; {
if n%2==1 {
count++
}
n /= 2
}
var count int
for ;n!=0; {
if n%2==1 {
count++
}
n /= 2
}
func sumZero(n int) []int {
var ans []int
if n%2==1 {
ans = append(ans, 0)
}
for i:=1;len(ans)!=n;i++ {
ans = append(ans, +i)
ans = append(ans, -i)
var ans []int
if n%2==1 {
ans = append(ans, 0)
}
for i:=1;len(ans)!=n;i++ {
ans = append(ans, +i)
ans = append(ans, -i)
class Solution:
def isValid(self, w: str, vo="aoeuiAOEUI", co="pyfgcrldhtnsqjkxbmwvzPYFGCRLDHTNSQJKXBMWVZ", n="7531902468") -> bool:
return len(w)>2 and any([c in vo for c in w])and any([c in co for c in w])and set(w)<set(vo+co+n)
def isValid(self, w: str, vo="aoeuiAOEUI", co="pyfgcrldhtnsqjkxbmwvzPYFGCRLDHTNSQJKXBMWVZ", n="7531902468") -> bool:
return len(w)>2 and any([c in vo for c in w])and any([c in co for c in w])and set(w)<set(vo+co+n)
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
m = 0
cc = 0
for n in nums:
if n != 1:
cc = 0
continue
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
m = 0
cc = 0
for n in nums:
if n != 1:
cc = 0
continue
func findMaxConsecutiveOnes(nums []int) int {
m := 0
cc := 0
for _, n := range nums {
if n != 1 {
cc = 0
continue
}
m := 0
cc := 0
for _, n := range nums {
if n != 1 {
cc = 0
continue
}
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize != 0:
return False
hand.sort()
groups = []
while hand:
s = hand[0]
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize != 0:
return False
hand.sort()
groups = []
while hand:
s = hand[0]
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
return "".join([s[(i+k)%len(s)] for i in range(len(s))])
def getEncryptedString(self, s: str, k: int) -> str:
return "".join([s[(i+k)%len(s)] for i in range(len(s))])
func hammingWeight(n int) int {
var w int
for ;n!=0; {
if n%2==1 {
w++
n--
} else {
n /= 2
var w int
for ;n!=0; {
if n%2==1 {
w++
n--
} else {
n /= 2
func uint32_to_bin_s(n uint32) string {
var b string
for ;n!=0; {
if n%2==1 {
n--
b = "1" + b
} else {
b = "0" + b
var b string
for ;n!=0; {
if n%2==1 {
n--
b = "1" + b
} else {
b = "0" + b
class Solution:
def minimumAverage(self, nums: List[int]) -> float:
avgs = []
while nums:
s, b = min(nums), max(nums)
nums.remove(s)
nums.remove(b)
avgs.append((s+b)/2)
def minimumAverage(self, nums: List[int]) -> float:
avgs = []
while nums:
s, b = min(nums), max(nums)
nums.remove(s)
nums.remove(b)
avgs.append((s+b)/2)
class Solution:
def check(self, nums: List[int]) -> bool:
if len(nums) == 1:
return True
s = min(nums)
for _ in range(len(nums)):
if s == nums[0] and nums[-1] != s:
break
def check(self, nums: List[int]) -> bool:
if len(nums) == 1:
return True
s = min(nums)
for _ in range(len(nums)):
if s == nums[0] and nums[-1] != s:
break
func convertToTitle(columnNumber int) string {
var bs []int
for ;columnNumber!=0; {
d := columnNumber%26
if d == 0 {
d = 26
columnNumber--
}
var bs []int
for ;columnNumber!=0; {
d := columnNumber%26
if d == 0 {
d = 26
columnNumber--
}
class Solution:
def countDigits(self, num: int) -> int:
return len(list(filter(lambda n:not num%n,[int(n)for n in str(num)])))
def countDigits(self, num: int) -> int:
return len(list(filter(lambda n:not num%n,[int(n)for n in str(num)])))
func runningSum(nums []int) []int {
var sum int
var sumarray []int
for _, n := range nums {
sum += n
sumarray = append(sumarray, sum)
}
return sumarray
var sum int
var sumarray []int
for _, n := range nums {
sum += n
sumarray = append(sumarray, sum)
}
return sumarray
class Solution:
def clearDigits(self, s: str) -> str:
ns = "01234567890"
s = list(s[::-1])
tl = len(s)
for c in s:
if c in ns:
tl -= 2
def clearDigits(self, s: str) -> str:
ns = "01234567890"
s = list(s[::-1])
tl = len(s)
for c in s:
if c in ns:
tl -= 2
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
p = ""
i = 0
while True:
b = False
cs = set()
for s in strs:
def longestCommonPrefix(self, strs: List[str]) -> str:
p = ""
i = 0
while True:
b = False
cs = set()
for s in strs:
class Solution:
def countLargestGroup(self, n: int) -> int:
groups = {}
l = 0
for i in range(1, n+1):
s = 0
for d in str(i):
s += int(d)
def countLargestGroup(self, n: int) -> int:
groups = {}
l = 0
for i in range(1, n+1):
s = 0
for d in str(i):
s += int(d)
class Solution:
def minimumCost(self, nums: List[int]) -> int:
c = nums[0]
nums = nums[1:]
s = min(nums)
nums.remove(s)
ss = min(nums)
return c + s + ss
def minimumCost(self, nums: List[int]) -> int:
c = nums[0]
nums = nums[1:]
s = min(nums)
nums.remove(s)
ss = min(nums)
return c + s + ss
func removeDuplicates(nums []int) int {
l := len(nums)
for i:=0; i<l-1; i++ {
if nums[i] == nums[i+1] {
for j:=i; j<l-1; j++ {
nums[j] = nums[j+1]
}
l--
l := len(nums)
for i:=0; i<l-1; i++ {
if nums[i] == nums[i+1] {
for j:=i; j<l-1; j++ {
nums[j] = nums[j+1]
}
l--
class Solution:truncateSentence=lambda _,s,k:" ".join(s.split()[:k])
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part, "", 1)
print(s)
return s
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part, "", 1)
print(s)
return s
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
flat = set()
for l in edges[:3]:
flat.add(l[0])
flat.add(l[1])
for e in flat:
center = True
def findCenter(self, edges: List[List[int]]) -> int:
flat = set()
for l in edges[:3]:
flat.add(l[0])
flat.add(l[1])
for e in flat:
center = True
class Solution:
def maxFrequencyElements(self, nums: List[int]) -> int:
freq = {}
h = 0
for n in nums:
freq[n] = freq.get(n, 0) + 1
if freq[n] > h:
h = freq[n]
def maxFrequencyElements(self, nums: List[int]) -> int:
freq = {}
h = 0
for n in nums:
freq[n] = freq.get(n, 0) + 1
if freq[n] > h:
h = freq[n]
class Solution:
def digit_sum(self, num) -> int:
s = 0
for d in str(num):
s += int(d)
return s
def maximumSum(self, nums) -> int:
def digit_sum(self, num) -> int:
s = 0
for d in str(num):
s += int(d)
return s
def maximumSum(self, nums) -> int:
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
combs = []
if len(nums) == 1:
return [nums]
if len(nums) == 2:
c1 = [nums[0], nums[1]]
c2 = [nums[1], nums[0]]
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
combs = []
if len(nums) == 1:
return [nums]
if len(nums) == 2:
c1 = [nums[0], nums[1]]
c2 = [nums[1], nums[0]]
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
for l in sorted(set(s)):
if distance[ord(l)-97] != s.rfind(l) - s.find(l) - 1:
return False
return True
def checkDistances(self, s: str, distance: List[int]) -> bool:
for l in sorted(set(s)):
if distance[ord(l)-97] != s.rfind(l) - s.find(l) - 1:
return False
return True
import pandas as pd
def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
return employees[:3]
def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
return employees[:3]
/**
* @return {Function}
*/
var createHelloWorld = function() {
return function(...args) {
return "Hello World"
}
* @return {Function}
*/
var createHelloWorld = function() {
return function(...args) {
return "Hello World"
}
func sortTheStudents(score [][]int, k int) [][]int {
for i:=0; i<len(score); i++ {
for j:=i; j<len(score); j++ {
if score[i][k] < score[j][k] {
score[i], score[j] = score[j], score[i]
}
}
}
for i:=0; i<len(score); i++ {
for j:=i; j<len(score); j++ {
if score[i][k] < score[j][k] {
score[i], score[j] = score[j], score[i]
}
}
}
func stringHash(s string, k int) string {
var result string
var chunk string
for _, c := range s {
chunk += string(c)
if len(chunk) == k {
var sum int
for _, char := range chunk {
var result string
var chunk string
for _, c := range s {
chunk += string(c)
if len(chunk) == k {
var sum int
for _, char := range chunk {
func contain(nums []int, target int) bool {
for _, n := range nums {
if n == target {
return true
}
}
return false
}
for _, n := range nums {
if n == target {
return true
}
}
return false
}
func sumOfGoodNumbers(nums []int, k int) int {
var sum int
for i, _ := range nums {
var good bool = true
if i-k >= 0 {
if nums[i-k] >= nums[i] {
good = false
}
var sum int
for i, _ := range nums {
var good bool = true
if i-k >= 0 {
if nums[i-k] >= nums[i] {
good = false
}
func count_set_bit(n int) int {
var count int
for ;n>0; {
if n % 2 == 1 {
n--
count++
}
n /= 2
var count int
for ;n>0; {
if n % 2 == 1 {
n--
count++
}
n /= 2
func wordPattern(pattern string, s string) bool {
var words []string
mapping := make(map[rune]string)
var lb int
for i:=0; i<len(s); i++ {
if i+1 == len(s) || s[i+1] == ' ' {
words = append(words, s[lb:i+1])
var words []string
mapping := make(map[rune]string)
var lb int
for i:=0; i<len(s); i++ {
if i+1 == len(s) || s[i+1] == ' ' {
words = append(words, s[lb:i+1])
func mergeAlternately(word1 string, word2 string) string {
var merged string
m := min(len(word1), len(word2))
for i:=0; i<m; i++ {
merged += string(word1[i])
merged += string(word2[i])
}
var merged string
m := min(len(word1), len(word2))
for i:=0; i<m; i++ {
merged += string(word1[i])
merged += string(word2[i])
}
func numberOfPairs(nums1 []int, nums2 []int, k int) int {
var count int
for _, i := range nums1 {
for _, j := range nums2 {
if i % (j*k) == 0 {
count++
}
}
var count int
for _, i := range nums1 {
for _, j := range nums2 {
if i % (j*k) == 0 {
count++
}
}
func moveZeroes(nums []int) {
for i, j := 0, 0; i<len(nums); i++ {
for;j<len(nums)&&nums[j]==0;j++{}
if j>=len(nums){
nums[i]=0
} else {
nums[i] = nums[j]
}
for i, j := 0, 0; i<len(nums); i++ {
for;j<len(nums)&&nums[j]==0;j++{}
if j>=len(nums){
nums[i]=0
} else {
nums[i] = nums[j]
}
func hasSameDigits(s string) bool {
for ;len(s)!=2; {
var t string
for i:=0; i<len(s)-1; i++ {
_s := (int(s[i]-48) + int(s[i+1]-48)) % 10
t += string(rune(_s+48))
}
s = t
for ;len(s)!=2; {
var t string
for i:=0; i<len(s)-1; i++ {
_s := (int(s[i]-48) + int(s[i+1]-48)) % 10
t += string(rune(_s+48))
}
s = t
func defangIPaddr(address string) string {
var defanged string
for _, c := range address {
if c == '.' {
defanged += "[.]"
} else {
defanged += string(c)
}
var defanged string
for _, c := range address {
if c == '.' {
defanged += "[.]"
} else {
defanged += string(c)
}
func pivotIndex(nums []int) int {
var sum int
for _, n := range nums {
sum += n
}
var ls int = 0
for i, n := range nums {
if ls == sum - n - ls {
var sum int
for _, n := range nums {
sum += n
}
var ls int = 0
for i, n := range nums {
if ls == sum - n - ls {
func contain(target int, array []int) bool {
for _, item := range array {
if item == target {
return true
}
}
return false
}
for _, item := range array {
if item == target {
return true
}
}
return false
}
func contain(target int, array []int) bool {
for _, v := range array {
if v == target {
return true
}
}
return false
}
for _, v := range array {
if v == target {
return true
}
}
return false
}
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is higher than the picked number
* 1 if num is lower than the picked number
* otherwise return 0
* func guess(num int) int;
*/
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is higher than the picked number
* 1 if num is lower than the picked number
* otherwise return 0
* func guess(num int) int;
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func transformArray(nums []int) []int {
o, e := 0, 0
for _, n := range nums {
if n%2==1 {
o++
} else {
e++
}
o, e := 0, 0
for _, n := range nums {
if n%2==1 {
o++
} else {
e++
}
func isArraySpecial(nums []int) bool {
for i:=0; i<len(nums)-1; i++ {
f, s := nums[i]%2, nums[i+1]%2
if f == s {
return false
}
}
return true
for i:=0; i<len(nums)-1; i++ {
f, s := nums[i]%2, nums[i+1]%2
if f == s {
return false
}
}
return true
func isAcronym(words []string, s string) bool {
if len(words) != len(s) {
return false
}
for i, c := range s {
if byte(c) != words[i][0] {
return false
}
if len(words) != len(s) {
return false
}
for i, c := range s {
if byte(c) != words[i][0] {
return false
}
func coloredCells(n int) int64 {
var ans int
for i:=1; i<=n; i++ {
if i == 1 {
ans += 1
} else {
ans += 4*(i)-4
}
var ans int
for i:=1; i<=n; i++ {
if i == 1 {
ans += 1
} else {
ans += 4*(i)-4
}
func reverse(s string) string {
var rev string
for i:=len(s)-1; i>=0; i-- {
rev += string(s[i])
}
return rev
}
func finalString(s string) string {
var rev string
for i:=len(s)-1; i>=0; i-- {
rev += string(s[i])
}
return rev
}
func finalString(s string) string {
func minimumRecolors(blocks string, k int) int {
m := len(blocks)
for i:=0; i<len(blocks)-k+1; i++ {
c := 0
for j:=0; j<k; j++ {
if blocks[i+j] == 'W' {
c++
}
m := len(blocks)
for i:=0; i<len(blocks)-k+1; i++ {
c := 0
for j:=0; j<k; j++ {
if blocks[i+j] == 'W' {
c++
}
func isStrictlyPalindromic(n int) bool {
return false
}
return false
}
func sort(list []int) []int {
for i:=0; i<len(list); i++ {
for j:=i; j<len(list); j++ {
if list[j] < list[i] {
list[i], list[j] = list[j], list[i]
}
}
}
for i:=0; i<len(list); i++ {
for j:=i; j<len(list); j++ {
if list[j] < list[i] {
list[i], list[j] = list[j], list[i]
}
}
}
func numberOfEmployeesWhoMetTarget(hours []int, target int) int {
var ans int
for _, hour := range hours {
if hour >= target {
ans++
}
}
return ans
var ans int
for _, hour := range hours {
if hour >= target {
ans++
}
}
return ans
func contain(target int, array []int) bool {
for _, v := range array {
if v == target {
return true
}
}
return false
}
for _, v := range array {
if v == target {
return true
}
}
return false
}
func abs(n int) int {
if n < 0 {
return n*-1
}
return n
}
func maximumStrongPairXor(nums []int) int {
var ans int
if n < 0 {
return n*-1
}
return n
}
func maximumStrongPairXor(nums []int) int {
var ans int
func containsNearbyDuplicate(nums []int, k int) bool {
for i:=0; i<len(nums); i++ {
for j:=1; j<=k && i+j<len(nums); j++ {
if nums[i] == nums[i+j] {
return true
}
}
}
for i:=0; i<len(nums); i++ {
for j:=1; j<=k && i+j<len(nums); j++ {
if nums[i] == nums[i+j] {
return true
}
}
}
func longestMonotonicSubarray(nums []int) int {
l := 0
le := 0
ci := 0
for _, v := range nums {
if v > le {
ci++
l := 0
le := 0
ci := 0
for _, v := range nums {
if v > le {
ci++
func searchInsert(nums []int, target int) int {
for i, v := range nums {
if target <= v {
return i
}
}
return len(nums)
}
for i, v := range nums {
if target <= v {
return i
}
}
return len(nums)
}
func contain(target int, arr []int) bool {
for _, v := range arr {
if v == target {
return true
}
}
return false
}
for _, v := range arr {
if v == target {
return true
}
}
return false
}
func tpow(x int) int {
p := 1
for ;x>1; x-- {
p *= 10
}
return p
}
func maximumValue(strs []string) int {
p := 1
for ;x>1; x-- {
p *= 10
}
return p
}
func maximumValue(strs []string) int {
func char_to_morse(char rune) string {
codes := []string{
".-","-...","-.-.","-..",".","..-.","--.",
"....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."}
return codes[char - 97]
}
codes := []string{
".-","-...","-.-.","-..",".","..-.","--.",
"....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."}
return codes[char - 97]
}
func hg_sum(x int, y int, mat [][]int) int {
var sum int
sum += (mat[y-1][x-1] + mat[y-1][x] + mat[y+1][x-1])
sum += mat[y][x]
sum += (mat[y-1][x+1] + mat[y+1][x] + mat[y+1][x+1])
return sum
}
func maxSum(grid [][]int) int {
var sum int
sum += (mat[y-1][x-1] + mat[y-1][x] + mat[y+1][x-1])
sum += mat[y][x]
sum += (mat[y-1][x+1] + mat[y+1][x] + mat[y+1][x+1])
return sum
}
func maxSum(grid [][]int) int {
type Cashier struct {
customers_done int
n int
discount int
products []int
prices []int
}
customers_done int
n int
discount int
products []int
prices []int
}
func numberOfLines(widths []int, s string) []int {
var line, lw int
line = 1
for _, c := range s {
w := widths[c-97]
if lw + w > 100 {
line++
lw = 0
var line, lw int
line = 1
for _, c := range s {
w := widths[c-97]
if lw + w > 100 {
line++
lw = 0
func divideArray(nums []int) bool {
pairs := make(map[int]int)
for _, n := range nums {
c, f := pairs[n]
if !f {
pairs[n] = 1
} else {
pairs[n] = c + 1
pairs := make(map[int]int)
for _, n := range nums {
c, f := pairs[n]
if !f {
pairs[n] = 1
} else {
pairs[n] = c + 1
func count(target int, arr []int) int {
var count int
for _, n := range arr {
if n == target {
count++
}
}
return count
var count int
for _, n := range arr {
if n == target {
count++
}
}
return count
func valid(stack []rune) bool {
var _s []rune
for _, p := range stack {
if p == '(' {
_s = append(_s, p)
} else {
if _s[len(_s)-1] == '(' {
_s = _s[:len(_s)-1]
var _s []rune
for _, p := range stack {
if p == '(' {
_s = append(_s, p)
} else {
if _s[len(_s)-1] == '(' {
_s = _s[:len(_s)-1]
https://leetcode.com/problems/binary-tree-preorder-traversal/submissions/1579203892/?envType=problem-list-v2&envId=stack
func reversePrefix(word string, ch byte) string {
var stack []rune
for _i, c := range word {
stack = append(stack, c)
if byte(c) == ch {
var r string
for i:=len(stack)-1; i>=0; i-- {
r += string(stack[i])
var stack []rune
for _i, c := range word {
stack = append(stack, c)
if byte(c) == ch {
var r string
for i:=len(stack)-1; i>=0; i-- {
r += string(stack[i])
func removeDuplicates(s string) string {
var stack []rune
for _, c := range s {
if len(stack) > 0 && stack[len(stack)-1] == c {
stack = stack[:len(stack)-1]
} else {
stack = append(stack, c)
}
var stack []rune
for _, c := range s {
if len(stack) > 0 && stack[len(stack)-1] == c {
stack = stack[:len(stack)-1]
} else {
stack = append(stack, c)
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
func makeGood(s string) string {
var stack []rune
if n < 0 {
return -n
}
return n
}
func makeGood(s string) string {
var stack []rune
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func all_same(arr []int) bool {
for _, v := range arr {
if v != arr[0] {
return false
}
}
return true
}
for _, v := range arr {
if v != arr[0] {
return false
}
}
return true
}
import "fmt"
type Stack struct {
values []int
}
func (stack *Stack) push(n int) {
stack.values = append(stack.values, n)
}
func (stack *Stack) pop() {
type Stack struct {
values []int
}
func (stack *Stack) push(n int) {
stack.values = append(stack.values, n)
}
func (stack *Stack) pop() {
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minOperations(logs []string) int {
depth := 0
for _, o := range logs {
if o == "../" {
if depth > 0 {
depth--
}
continue
depth := 0
for _, o := range logs {
if o == "../" {
if depth > 0 {
depth--
}
continue
func maxDepth(s string) int {
var depth, max_depth int
for _, c := range s {
if c == '(' {
depth++
}
if c == ')' {
depth--
var depth, max_depth int
for _, c := range s {
if c == '(' {
depth++
}
if c == ')' {
depth--
type MyStack struct {
values []int
len int
}
func Constructor() MyStack {
var stack MyStack
values []int
len int
}
func Constructor() MyStack {
var stack MyStack
// Stack implimentatin
type MyStack struct {
values []int
len int
}
func (this *MyStack) Push(x int) {
this.values = append(this.values, x)
type MyStack struct {
values []int
len int
}
func (this *MyStack) Push(x int) {
this.values = append(this.values, x)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/
func nextGreaterElement(nums1 []int, nums2 []int) []int {
var ans []int
for _, n := range nums1 {
f := false
g := -1
for _, v := range nums2 {
if f && v > n {
g = v
var ans []int
for _, n := range nums1 {
f := false
g := -1
for _, v := range nums2 {
if f && v > n {
g = v
func maximumWealth(accounts [][]int) int {
var max_wealth int
for _, customer := range accounts {
var wealth int
for _, bank := range customer {
wealth += bank
}
if wealth > max_wealth {
var max_wealth int
for _, customer := range accounts {
var wealth int
for _, bank := range customer {
wealth += bank
}
if wealth > max_wealth {
type RecentCounter struct {
pings []int
}
func Constructor() RecentCounter {
var rc RecentCounter
return rc
pings []int
}
func Constructor() RecentCounter {
var rc RecentCounter
return rc
type ParkingSystem struct {
big int
medium int
small int
}
func Constructor(big int, medium int, small int) ParkingSystem {
big int
medium int
small int
}
func Constructor(big int, medium int, small int) ParkingSystem {
import "fmt"
func split_words(sentence string) []string {
var words []string
l, i := 0, 0
for ; i<len(sentence); i++ {
if sentence[i] == ' ' {
words = append(words, sentence[l:i])
l = i+1
func split_words(sentence string) []string {
var words []string
l, i := 0, 0
for ; i<len(sentence); i++ {
if sentence[i] == ' ' {
words = append(words, sentence[l:i])
l = i+1
func unequalTriplets(nums []int) int {
l := len(nums)
var count int
for i:=0; i<l-2; i++ {
for j:=i+1; j<l-1; j++ {
for k:=j+1; k<l; k++ {
if (
nums[i] != nums[j] &&
l := len(nums)
var count int
for i:=0; i<l-2; i++ {
for j:=i+1; j<l-1; j++ {
for k:=j+1; k<l; k++ {
if (
nums[i] != nums[j] &&
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getDecimalValue(head *ListNode) int {
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getDecimalValue(head *ListNode) int {
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func middleNode(head *ListNode) *ListNode {
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func middleNode(head *ListNode) *ListNode {
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode? next;
* ListNode([this.val = 0, this.next]);
* }
*/
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode? next;
* ListNode([this.val = 0, this.next]);
* }
*/
class Solution {
bool isRobotBounded(String instructions) {
List<int> direction = [0, 1], cordinates = [0, 0];
instructions.runes.forEach((int r) {
var c = new String.fromCharCode(r);
if (c == 'G') {
cordinates[0] += direction[0];
cordinates[1] += direction[1];
bool isRobotBounded(String instructions) {
List<int> direction = [0, 1], cordinates = [0, 0];
instructions.runes.forEach((int r) {
var c = new String.fromCharCode(r);
if (c == 'G') {
cordinates[0] += direction[0];
cordinates[1] += direction[1];
func mySqrt(x int) int {
for n := range x+1 {
if n*n >= x || (n+1)*(n+1) > x {
return n
}
}
return 0
}
for n := range x+1 {
if n*n >= x || (n+1)*(n+1) > x {
return n
}
}
return 0
}
func titleToNumber(columnTitle string) int {
p := 1
var n int
for i:=len(columnTitle)-1; i>=0; i++ {
c = columnTitle[i]
n += (int(c)-64)*p
p *= 26
}
p := 1
var n int
for i:=len(columnTitle)-1; i>=0; i++ {
c = columnTitle[i]
n += (int(c)-64)*p
p *= 26
}
func contain_duplicate(s string) bool {
for _, c := range s {
var count int
for _, cc := range s {
if c == cc {
count++
}
}
for _, c := range s {
var count int
for _, cc := range s {
if c == cc {
count++
}
}
func atoi(s string) int {
var n int
for _, c := range s {
n = (n*10) + int(c-48)
}
return n
}
func is_number(s string) bool {
var n int
for _, c := range s {
n = (n*10) + int(c-48)
}
return n
}
func is_number(s string) bool {
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
def remove_nth_from_end(head, n)
if not head or not head.next then
return nil
end
len = 0
th = head
while th do
if not head or not head.next then
return nil
end
len = 0
th = head
while th do
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeElements(head *ListNode, val int) *ListNode {
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeElements(head *ListNode, val int) *ListNode {
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// LinkedList //
import "fmt"
// type ListNode struct {
// Val int
// Next *ListNode
// }
type MyLinkedList struct {
import "fmt"
// type ListNode struct {
// Val int
// Next *ListNode
// }
type MyLinkedList struct {
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// @leet start
type BrowserHistoryNode struct {
Url string
Back *BrowserHistoryNode
Forward *BrowserHistoryNode
}
type BrowserHistoryNode struct {
Url string
Back *BrowserHistoryNode
Forward *BrowserHistoryNode
}
func isPerfectSquare(num int) bool {
n := 1
for {
s := n * n
if s == num {
return true
}
if s > num {
n := 1
for {
s := n * n
if s == num {
return true
}
if s > num {
func SliceFind(arr []int, target int) int {
for i, v := range arr {
if v == target {
return i
}
}
return -1
}
for i, v := range arr {
if v == target {
return i
}
}
return -1
}
func getMaximumGenerated(n int) int {
if n == 0 {
return 0
}
arr := []int{0, 1}
for len(arr) < n + 1 {
l := len(arr)
i := l / 2
if n == 0 {
return 0
}
arr := []int{0, 1}
for len(arr) < n + 1 {
l := len(arr)
i := l / 2
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func minsumpair(nums []int) int {
var min_sum int = (2000 * 50) + 1
var min_inexd int = -1
for i:=0; i<len(nums)-1; i++ {
s := nums[i] + nums[i+1]
if s < min_sum {
min_sum = s
min_inexd = i
var min_sum int = (2000 * 50) + 1
var min_inexd int = -1
for i:=0; i<len(nums)-1; i++ {
s := nums[i] + nums[i+1]
if s < min_sum {
min_sum = s
min_inexd = i
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
n = 0
while nums:
f = nums.pop(0)
if nums:
l = nums.pop()
else:
def findTheArrayConcVal(self, nums: List[int]) -> int:
n = 0
while nums:
f = nums.pop(0)
if nums:
l = nums.pop()
else:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
/**
* Definition for a Node.
* type Node struct {
* Val int
* Prev *Node
* Next *Node
* Child *Node
* }
* Definition for a Node.
* type Node struct {
* Val int
* Prev *Node
* Next *Node
* Child *Node
* }
class Solution:
def findRestaurant(self, list1: list[str], list2: list[str]) -> list[str]:
lis = len(list1+list2)+1
ans = []
for w1 in list1:
if w1 in list2:
w1i = list1.index(w1)
w2i = list2.index(w1)
def findRestaurant(self, list1: list[str], list2: list[str]) -> list[str]:
lis = len(list1+list2)+1
ans = []
for w1 in list1:
if w1 in list2:
w1i = list1.index(w1)
w2i = list2.index(w1)
type Char struct {
Value string
Prev *Char
Next *Char
}
type TextEditor struct {
Cursor *Char
Value string
Prev *Char
Next *Char
}
type TextEditor struct {
Cursor *Char
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
# @leet start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
content_match = {}
for path in paths:
dir, *files_and_contains = path.split(" ")
for file_and_contain in files_and_contains:
fpp = file_and_contain.find("(")
filename = file_and_contain[:fpp]
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
content_match = {}
for path in paths:
dir, *files_and_contains = path.split(" ")
for file_and_contain in files_and_contains:
fpp = file_and_contain.find("(")
filename = file_and_contain[:fpp]
func numJewelsInStones(jewels string, stones string) int {
var count int
for _, j := range jewels {
for _, s := range stones {
if j == s {
count++
}
}
var count int
for _, j := range jewels {
for _, s := range stones {
if j == s {
count++
}
}
class Solution:
def findWords(self, words: List[str]) -> List[str]:
rows = [
"qwertyuiop",
"asdfghjkl",
"zxcvbnm",
]
ans = []
def findWords(self, words: List[str]) -> List[str]:
rows = [
"qwertyuiop",
"asdfghjkl",
"zxcvbnm",
]
ans = []
class Solution:
def isLowerOrEqual(self, word1, word2, order) -> bool:
for i in range(min(len(word1), len(word2))):
lc, rc = word1[i], word2[i]
if lc != rc:
if order.find(lc) < order.find(rc):
return True
else:
def isLowerOrEqual(self, word1, word2, order) -> bool:
for i in range(min(len(word1), len(word2))):
lc, rc = word1[i], word2[i]
if lc != rc:
if order.find(lc) < order.find(rc):
return True
else:
class Solution:
def checkIfPangram(self, sentence: str) -> bool:
return len(set(sentence)) == 26
def checkIfPangram(self, sentence: str) -> bool:
return len(set(sentence)) == 26
# @leet start
# @param {Integer[]} arr
# @param {Integer} a
# @param {Integer} b
# @param {Integer} c
# @return {Integer}
def count_good_triplets(arr, a, b, c)
count = 0
# @param {Integer[]} arr
# @param {Integer} a
# @param {Integer} b
# @param {Integer} c
# @return {Integer}
def count_good_triplets(arr, a, b, c)
count = 0
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
while "-" in s:
s = s.replace("-", "")
s = s.upper()
fk = ""
while True:
if len(s) <= k:
def licenseKeyFormatting(self, s: str, k: int) -> str:
while "-" in s:
s = s.replace("-", "")
s = s.upper()
fk = ""
while True:
if len(s) <= k:
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
if len(s1) != len(s2):
return False
if set(s1) != set(s2):
return False
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
if len(s1) != len(s2):
return False
if set(s1) != set(s2):
return False
class Solution:
def lastStoneWeight(self, stones: list[int]) -> int:
stones.sort()
print(stones)
while len(stones) > 1:
y = stones.pop()
x = stones.pop()
if x == y:
def lastStoneWeight(self, stones: list[int]) -> int:
stones.sort()
print(stones)
while len(stones) > 1:
y = stones.pop()
x = stones.pop()
if x == y:
class Solution:
def flipAndInvertImage(self, image: list[list[int]]) -> list[list[int]]:
for i in range(len(image)):
row = image[i]
row = row[::-1]
for j in range(len(row)):
row[j] = [1, 0][row[j]]
image[i] = row
def flipAndInvertImage(self, image: list[list[int]]) -> list[list[int]]:
for i in range(len(image)):
row = image[i]
row = row[::-1]
for j in range(len(row)):
row[j] = [1, 0][row[j]]
image[i] = row
class Solution:
def lastSubstring(self, s: str) -> str:
alphas = "abcdefghijklmnopqrstuvwxyz"
i = 0
for a in alphas[::-1]:
f = s.find(a)
if f != -1:
i = f
def lastSubstring(self, s: str) -> str:
alphas = "abcdefghijklmnopqrstuvwxyz"
i = 0
for a in alphas[::-1]:
f = s.find(a)
if f != -1:
i = f
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
l = len(nums)
seen = set()
for n in reversed(nums):
if n in seen:
break
seen.add(n)
def minimumOperations(self, nums: List[int]) -> int:
l = len(nums)
seen = set()
for n in reversed(nums):
if n in seen:
break
seen.add(n)