abh - HTMLify profile

abh's Profile Picture

abh

501 Files

101798 Views

Latest files of /abh/lc

LeetCode - Number of Good Pairs - Rust abh/lc/1512.rs
435 Views
1 Comments
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;
}
LeetCode- A Number After a Double Reversal - Python abh/lc/2119.py
321 Views
0 Comments
class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if not num: return True
return num % 10
LeetCode - A Number After a Double Reversal - Rust abh/lc/2119.rs
350 Views
0 Comments
impl Solution {
pub fn is_same_after_reversals(num: i32) -> bool {
if (num != 0){
return num % 10 != 0;
}
else{
return true;
}
LeetCode - A Number After a Double Reversal - Javascript abh/lc/2119.js
230 Views
0 Comments
/**
* @param {number} num
* @return {boolean}
*/
var isSameAfterReversals = function(num) {
if (num)
return num % 10 != 0;
else
LeetCode - Big Countries abh/lc/595.sql
338 Views
0 Comments
SELECT name, population, area FROM world WHERE area >= 3000000 or population >= 25000000;
LeetCode - Find Customer Referee - MySQL abh/lc/584.sql
319 Views
0 Comments
SELECT name FROM Customer WHERE referee_id != 2 OR referee_id IS NULL;
LeetCode - Recyclable and Low Fat Products - MySQL abh/lc/1757.sql
310 Views
0 Comments
SELECT product_id FROM Products WHERE low_fats = 'Y' AND recyclable = 'Y';
LeetCode - Invalid Tweets - MySQL abh/lc/1683.sql
346 Views
0 Comments
SELECT tweet_id FROM Tweets WHERE CHAR_LENGTH(content) > 15;
LeetCode - Article Views I - MySQL abh/lc/1148.sql
379 Views
0 Comments
SELECT DISTINCT author_id AS id FROM Views WHERE author_id = viewer_id ORDER BY author_id;
LeetCode - To Be Or Not To Be - JavaScript abh/lc/2704.js
245 Views
0 Comments
/**
* @param {string} val
* @return {Object}
*/
var expect = function(val) {
return {"toBe":
function (valu){
if (valu === val)
LeetCode - Create Hello World Function - JavaScript abh/lc/2667.js
230 Views
0 Comments
/**
* @return {Function}
*/
var createHelloWorld = function() {

return function(...args) {
return "Hello World";
}
LeetCode - Counter - JavaScript abh/lc/2620.js
212 Views
0 Comments
/**
* @param {number} n
* @return {Function} counter
*/
var createCounter = function(n) {
let count = n;
return function() {
return count++;
LeetCode - Counter II - JavaScript abh/lc/2665.js
213 Views
0 Comments
/**
* @param {integer} init
* @return { increment: Function, decrement: Function, reset: Function }
*/
var createCounter = function(init) {
return {
"init": init,
"count": init,
LeetCode - Function Composition - JavaScript abh/lc/2629.js
198 Views
0 Comments
/**
* @param {Function[]} functions
* @return {Function}
*/
var compose = function(functions) {

return function(x) {
functions.reverse();
LeetCode - Return Length of Arguments Passed - JavaScript abh/lc/2703.js
261 Views
0 Comments
/**
* @param {...(null|boolean|number|string|Array|Object)} args
* @return {number}
*/
var argumentsLength = function(...args) {
return args.length;
};

LeetCode - Allow One Function Call - JavaScript abh/lc/2666.js
224 Views
0 Comments
/**
* @param {Function} fn
* @return {Function}
*/
var once = function(fn) {
let called = false;
return function(...args){
if (called)
LeetCode - Find Followers Count - MySQL abh/lc/1729.sql
331 Views
0 Comments
SELECT user_id, count(follower_id) as followers_count FROM Followers GROUP BY user_id ORDER BY user_id;
LeetCode - Add Two Integers - Python abh/lc/2235.py
333 Views
0 Comments
class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2
LeetCode - Add Two Integers - JavaScript abh/lc/2235.js
234 Views
0 Comments
/**
* @param {number} num1
* @param {number} num2
* @return {number}
*/
var sum = function(num1, num2) {
return num1 + num2;
};
LeetCode - Add Two Integers - Rust abh/lc/2235.rs
350 Views
0 Comments
impl Solution {
pub fn sum(num1: i32, num2: i32) -> i32 {
return num1 + num2;
}
}
LeetCode - Add Two Integers - Ruby abh/lc/2235.rb
411 Views
1 Comments
# @param {Integer} num1
# @param {Integer} num2
# @return {Integer}
def sum(num1, num2)
return num1 + num2
end
LeetCode - Add Two Integers - Scala abh/lc/2235.scala
373 Views
1 Comments
object Solution {
def sum(num1: Int, num2: Int): Int = {
return num1 + num2;
}
}
LeetCode - Fibonacci Number - Python abh/lc/509.py
367 Views
0 Comments
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):
LeetCode - Fibonacci Number - Rust abh/lc/509.rs
353 Views
1 Comments
impl Solution {
pub fn fib(n: i32) -> i32 {
if (n == 0){
return 0;
}
if (n == 1){
return 1;
}
LeetCode - Fibonacci Number - JavaScript abh/lc/509.js
217 Views
1 Comments
/**
* @param {number} n
* @return {number}
*/
var fib = function(n) {
if (n == 0)
return 0;
if (n == 1)
LeetCode - Matrix Diagonal Sum - Python abh/lc/1572.py
330 Views
0 Comments
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]
LeetCode - Create Target Array in the Given Order - Python abh/lc/1389.py
335 Views
0 Comments
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

LeetCode - Shuffle String - Python abh/lc/1528.py
432 Views
0 Comments
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
LeetCode - Chunk Array - JavaScript abh/lc/2677.js
204 Views
0 Comments
/**
* @param {Array} arr
* @param {number} size
* @return {Array}
*/
var chunk = function(arr, size) {
const chunked = [];
let chunk = [];
LeetCode - Separate the Digits in an Array - Python abh/lc/2553.py
355 Views
0 Comments
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 = []
LeetCode - How Many Numbers Are Smaller Than the Current Number - Python abh/lc/1365.py
318 Views
0 Comments
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
LeetCode - Find Champion I - Python abh/lc/2923.py
328 Views
1 Comments
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]
LeetCode - Patients With a Condition - MySQL abh/lc/1527.sql
341 Views
4 Comments
# Write your MySQL query statement below
SELECT * FROM patients
WHERE conditions LIKE '% DIAB1%' or conditions LIKE 'DIAB1%' ;
LeetCode - Reverse Only Letters - Python abh/lc/917.py
346 Views
0 Comments
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)
LeetCode - Search a 2D Matrix - Python abh/lc/74.py
458 Views
0 Comments
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
if target in row:
return True
return False
LeetCode - First Letter to Appear Twice - Python abh/lc/2351.py
343 Views
0 Comments
class Solution:
def repeatedCharacter(self, s: str) -> str:
seen = set()
for c in s:
if c in seen:
return c
seen.add(c)
LeetCode - First Letter to Appear Twice - JavaScript abh/lc/2351.js
225 Views
0 Comments
/**
* @param {string} s
* @return {character}
*/
var repeatedCharacter = function(s) {
seen = [];
for (let i=0;i<s.length;i++){
if (seen.includes(s[i]))
LeetCode - Assign Cookies - Python abh/lc/455.py
294 Views
0 Comments
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
LeetCode - Convert an Array Into a 2D Array With Conditions - Python abh/lc/2610.py
315 Views
0 Comments
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)
LeetCode - Number of Laser Beams in a Bank - Python abh/lc/2125.py
295 Views
0 Comments
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")
LeetCode - Number of Laser Beams in a Bank - C# abh/lc/2125.cs
358 Views
1 Comments
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')
LeetCode - Time Needed to Rearrange a Binary String - Python abh/lc/2380.py
333 Views
0 Comments
class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
secs = 0
while "01" in s:
s = s.replace("01", "10")
secs += 1
return secs
LeetCod3 - Check if Array is Good - Python abh/lc/2784.py
320 Views
0 Comments
class Solution:
def isGood(self, nums: List[int]) -> bool:
nums.sort()
good = list(range(1, len(nums))) + [len(nums)-1]
return nums == good
LeetCode - Insert Delete GetRandom O(1) - Python abh/lc/380.py
344 Views
0 Comments
from random import choice
class RandomizedSet:

def __init__(self):
self.values = []

def insert(self, val: int) -> bool:
if val in self.values:
LeetCode - Insert Delete GetRandom O(1) - Duplicates allowed - Python abh/lc/381.py
284 Views
0 Comments
from random import choice
class RandomizedCollection:

def __init__(self):
self.values = []

def insert(self, val: int) -> bool:
exist = not val in self.values
LeetCode - Maximum Odd Binary Number - Python abh/lc/2864.py
278 Views
0 Comments
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"
LeetCode - Squares of a Sorted Array - Python abh/lc/977.py
298 Views
0 Comments
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
return list(sorted(map(lambda a:a*a, nums)))
LeetCode - Largest Positive Integer That Exists With Its Negative - Python abh/lc/2441.py
252 Views
0 Comments
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:
LeetCode - Merge Sorted Array - Python abh/lc/88.py
220 Views
0 Comments
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)
LeetCode | Reverse Vowels of a String | Python abh/lc/345.py
215 Views
0 Comments
class Solution:
def reverseVowels(self, s: str) -> str:
rvs = ""
for c in s[::-1]:
if c in "aeiouAEIOU":
rvs += c
ns = ""
p = 0
LeetCode - Take Gifts From the Richest Pile - Python abh/lc/2558.py
191 Views
0 Comments
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)
LeetCode - Majority Element - Python abh/lc/169.py
184 Views
0 Comments
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
LeetCode - Check If a Word Occurs As a Prefix of Any Word in a Sentence - Python abh/lc/1455.py
187 Views
0 Comments
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
LeetCode - Linked List Random Node - Python abh/lc/382.py
163 Views
0 Comments
# 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:

LeetCode - Random Pick Index - Python abh/lc/398.py
167 Views
0 Comments
from random import choice

class Solution:

def __init__(self, nums: List[int]):
self.nums = nums

def pick(self, target: int) -> int:
LeetCode - Final Array State After K Multiplication Operations I - Python abh/lc/3264.py
153 Views
0 Comments
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
LeeCode - Rotate String - Python abh/lc/796.py
192 Views
0 Comments
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
LeetCode - Lemonade Change - Python abh/lc/860.py
202 Views
0 Comments
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:
LeetCode - Final Prices With a Special Discount in a Shop - Python abh/lc/1475.py
189 Views
0 Comments
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
LeetCode - Check If N and Its Double Exist - Python abh/lc/1346.py
169 Views
0 Comments
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
LootCode - Score of a String - Python abh/lc/3110.py
161 Views
0 Comments
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])
LeetCode - Find the Maximum Achievable Number - Python abh/lc/2769.py
161 Views
0 Comments
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + (t*2)
LeetCode - Delete Characters to Make Fancy String - Python abh/lc/1957.py
161 Views
0 Comments
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
LeetCode - Minimum String Length After Removing Substrings - Python abh/lc/2696.py
167 Views
0 Comments
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)
LeetCode - Reverse Odd Levels of Binary Tree - Python abh/lc/2415.py
246 Views
0 Comments
# 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]:
LeetCode - Number of Senior Citizens - Python abh/lc/2678.py
199 Views
0 Comments
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])))
LeetCode - Sum of Digits of String After Convert - Python abh/lc/1945.py
157 Views
0 Comments
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:
LeetCode - Check if All Characters Have Equal Number of Occurrences - Python abh/lc/1941.py
208 Views
0 Comments
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
LeetCode - Circular Sentence - Python abh/lc/2490.py
189 Views
0 Comments
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
LeetCode - Uncommon Words from Two Sentences - Python abh/lc/884.py
147 Views
0 Comments
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)
LeetCode - Make Two Arrays Equal by Reversing Subarrays - Python abh/lc/1460.py
172 Views
0 Comments
class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
return sorted(target) == sorted(arr)
LeetCode - Sort the People - Python abh/lc/2418.py
187 Views
0 Comments
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)]
LeetCode - Kth Distinct String in an Array - Python abh/lc/2053.py
162 Views
0 Comments
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)
LeetCode - Sort Array by Increasing Frequency - Python abh/lc/1636.py
183 Views
0 Comments
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
LeetCode - Count the Number of Consistent Strings - Python abh/lc/1684.py
214 Views
0 Comments
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
return len(list(filter(lambda e:set(e)<=set(allowed),words)))
LeetCode - Apply Operations to an Array - Python abh/lc/2460.py
161 Views
0 Comments
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)
LeetCode - Number Complement - Python abh/lc/476.py
148 Views
0 Comments
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)
LeetCode - Shuffle an Array - Python abh/lc/384.py
167 Views
0 Comments
from random import shuffle

class Solution:

def __init__(self, nums: List[int]):
self.list = nums
self.orgi = nums.copy()

LootCode - Minimum Bit Flips to Convert Number - Python abh/lc/2220.py
159 Views
0 Comments
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]:
LeetCode - Maximum Score After Splitting a String - Python abh/lc/1422.py
146 Views
0 Comments
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:
LootCode - Letter Combinations of a Phone Number - Python abh/lc/17.py
151 Views
0 Comments
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
pad = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
LeetCode - Number of Ways to Split Array - Python abh/lc/2270.py
227 Views
0 Comments
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
LeetCode - Reformat Date - Python abh/lc/1507.py
147 Views
0 Comments
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"
]
LeetCode - Number of Segments in a String - Python abh/lc/434.py
154 Views
0 Comments
class Solution:
def countSegments(self, s: str) -> int:
n = 0
f = True
for c in s+" ":
if c == " ":
if not f:
n += 1
LeetCode - Find the Index of the First Occurrence in a String - Python abh/lc/28.py
148 Views
0 Comments
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])
LeetCode - Sorting the Sentence - Python abh/lc/1859.py
193 Views
0 Comments
class Solution:
def sortSentence(self, s: str) -> str:
return " ".join([w[:-1] for w in sorted(s.split(), key=lambda e:int(e[-1]))])
LeetCode - Convert Date to Binary - Python abh/lc/3280.py
162 Views
0 Comments
class Solution:
def convertDateToBinary(self, date: str) -> str:
return "-".join([bin(int(e))[2:] for e in date.split("-")])
LeetCode - Kids With the Greatest Number of Candies - Python abh/lc/1431.py
140 Views
0 Comments
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
return [c + extraCandies >= max(candies) for c in candies]
LeetCode - Count Prefix and Suffix Pairs I - Python abh/lc/3042.py
180 Views
0 Comments
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)):
LeetCode - Valid Parentheses - Python abh/lc/20.py
174 Views
0 Comments
class Solution:
def isValid(self, s: str) -> bool:
stack = []
m = {
')': '(',
'}': '{',
']': '[',
}
LeetCode - Kth Largest Element in a Stream - Python abh/lc/703.py
138 Views
0 Comments
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:
LeetCode - Counting Words With a Given Prefix - Python abh/lc/2185.py
146 Views
0 Comments
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
return len(list(filter(lambda e:e.startswith(pref), words)))
LeetCode - Remove Element - Python abh/lc/27.py
141 Views
0 Comments
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
while val in nums:
nums.remove(val)
return len(nums)
LeetCode - Number of Even and Odd Bits - Python abh/lc/2595.py
134 Views
0 Comments
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
LeetCode - Words Subsets - Python abh/lc/916.py
0 Views
0 Comments
File is hidden
LeetCode - Add Two Numbers - Python abh/lc/2.py
146 Views
1 Comments
# 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
LeetCode - String Matching in an Array - Python abh/lc/1408.py
164 Views
0 Comments
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_:
LeetCode - Construct K Palindrome Strings - Python abh/lc/1400.py
127 Views
0 Comments
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
LeetCode - Validate IP Address - Python abh/lc/468.py
153 Views
0 Comments
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:
LeetCode - Print in Order - Python abh/lc/1114.py
146 Views
0 Comments
from time import sleep

class Foo:
def __init__(self):
self.last_print = 0


def first(self, printFirst: 'Callable[[], None]') -> None:
LeetCode - Print FooBar Alternately - Python abh/lc/1115.py
141 Views
0 Comments
from time import sleep

class FooBar:
def __init__(self, n):
self.n = n
self.next = "foo"


LeetCode - Merge Two Sorted Lists - Python abh/lc/21.py
155 Views
0 Comments
# 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)
LeetCode - Single Number - Python abh/lc/136.py
150 Views
0 Comments
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return sorted(nums, key=lambda e:nums.count(e))[0]
LeetCode - Merge k Sorted Lists - Python abh/lc/23.py
135 Views
0 Comments
# 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):
LeetCode - Valid Palindrome - Python abh/lc/125.py
171 Views
0 Comments
class Solution:
def isPalindrome(self, s: str) -> bool:
fls = "".join([c for c in s.lower() if c in "pyfgcrlaoeuidhtnsqjkxbmwvz1234567890"])
return fls == fls[::-1]

LeetCode - Permutations - Python abh/lc/46.py
182 Views
0 Comments
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)
LeetCode - Reverse String - Python abh/lc/344.py
135 Views
0 Comments
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]
LeetCode - Sum of Unique Elements - Go abh/lc/1748.go
149 Views
0 Comments
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 {
LeetCode - Hamming Distance - Go abh/lc/461.go
162 Views
0 Comments
func int_to_binary(n int) string {
var b string = ""
for ;n!=0; {
if n % 2 == 0 {
b = "0" + b
} else {
b = "1" + b
}
LeetCode - Keep Multiplying Found Values by Two - Go abh/lc/2154.go
142 Views
0 Comments
func findFinalValue(nums []int, original int) int {
for ;true; {
f := false
for _, n := range nums {
if n == original {
f = true
break
}
LeetCode - Reverse Integer - Go abh/lc/7.go
150 Views
1 Comments
func int_to_str(n int) string {
s := ""
if n < 0 {
s += "-"
n *= -1
}
for ;n!=0; {
m := n % 10
LeetCode - Reverse Integer - Python abh/lc/7.py
150 Views
0 Comments
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
LeetCode - Two Sum II - Input Array Is Sorted - Python abh/lc/167.py
159 Views
0 Comments
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]
LeetCode - Two Sum II - Input Array Is Sorted - Go abh/lc/167.go
136 Views
0 Comments
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 {
LeetCode - Valid Anagram - Python abh/lc/242.py
145 Views
0 Comments
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
LeetCode - Counting Bits - Go abh/lc/338.go
148 Views
0 Comments
func one_count(n int) int {
var count int
for ;n!=0; {
if n%2==1 {
count++
}
n /= 2
}
LeetCode - Find N Unique Integers Sum up to Zero - Go abh/lc/1304.go
140 Views
0 Comments
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)
LeetCode - Valid Word - Python abh/lc/3136.py
143 Views
0 Comments
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)
LeetCode - Max Consecutive Ones - Python abh/lc/485.py
142 Views
0 Comments
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
m = 0
cc = 0
for n in nums:
if n != 1:
cc = 0
continue
LeetCode - Max Consecutive Ones - Go abh/lc/485.go
124 Views
0 Comments
func findMaxConsecutiveOnes(nums []int) int {
m := 0
cc := 0
for _, n := range nums {
if n != 1 {
cc = 0
continue
}
LeetCode - Hand of Straights - Python abh/lc/846.py
128 Views
0 Comments
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]
LeetCode - Find the Encrypted String - Python abh/lc/3210.py
134 Views
0 Comments
class Solution:
def getEncryptedString(self, s: str, k: int) -> str:
return "".join([s[(i+k)%len(s)] for i in range(len(s))])
LeetCode - Number of 1 Bits - Go abh/lc/191.go
188 Views
0 Comments
func hammingWeight(n int) int {
var w int
for ;n!=0; {
if n%2==1 {
w++
n--
} else {
n /= 2
LeetCode - Reverse Bits - Go abh/lc/190.go
142 Views
0 Comments
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
LeetCode - Minimum Average of Smallest and Largest Elements - Python abh/lc/3194.py
163 Views
0 Comments
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)
LeetCode - Check if Array Is Sorted and Rotated - Python abh/lc/1752.py
131 Views
0 Comments
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
LeetCode - Excel Sheet Column Title - Go abh/lc/168.go
135 Views
0 Comments
func convertToTitle(columnNumber int) string {
var bs []int
for ;columnNumber!=0; {
d := columnNumber%26
if d == 0 {
d = 26
columnNumber--
}
LeetCode - Count the Digits That Divide a Number - Python abh/lc/2520.py
145 Views
0 Comments
class Solution:
def countDigits(self, num: int) -> int:
return len(list(filter(lambda n:not num%n,[int(n)for n in str(num)])))
LeetCode - Running Sum of 1d Array - Go abh/lc/1480.go
146 Views
0 Comments
func runningSum(nums []int) []int {
var sum int
var sumarray []int
for _, n := range nums {
sum += n
sumarray = append(sumarray, sum)
}
return sumarray
LeetCode - Clear Digits - Python abh/lc/3174.py
138 Views
0 Comments
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
LeetCode - Longest Common Prefix - Python abh/lc/14.py
155 Views
0 Comments
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
p = ""
i = 0
while True:
b = False
cs = set()
for s in strs:
LeetCode - Count Largest Group - Python abh/lc/1399.py
140 Views
0 Comments
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)
LeetCode - Divide an Array Into Subarrays With Minimum Cost I - Python abh/lc/3010.py
138 Views
0 Comments
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
LeetCode - Remove Duplicates from Sorted Array - Go abh/lc/26.go
127 Views
0 Comments
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--
LeetCode - Truncate Sentence - Python abh/lc/1816.py
130 Views
0 Comments
class Solution:truncateSentence=lambda _,s,k:" ".join(s.split()[:k])
LeetCode - Remove All Occurrences of a Substring - Python abh/lc/1910.py
117 Views
0 Comments
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part, "", 1)
print(s)
return s
LeetCode - Find Center of Star Graph - Python abh/lc/1791.py
152 Views
0 Comments
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
LeetCode - Count Elements With Maximum Frequency - Python abh/lc/3005.py
136 Views
0 Comments
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]
LeetCode - Max Sum of a Pair With Equal Sum of Digits - Python abh/lc/2342.py
134 Views
0 Comments
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:
LeetCode - Permutations II - Python abh/lc/47.py
149 Views
0 Comments
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]]
LeetCode - Check Distances Between Same Letters - Python abh/lc/2399.py
124 Views
0 Comments
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
LeetCode - Display the First Three Rows - Python abh/lc/2879.py
128 Views
0 Comments
import pandas as pd

def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame:
return employees[:3]
LeetCode - Create Hello World Function - JavaScript abh/lc/2776.js
127 Views
0 Comments
/**
* @return {Function}
*/
var createHelloWorld = function() {

return function(...args) {
return "Hello World"
}
LeetCode - Sort the Students by Their Kth Score - Go abh/lc/2545.go
136 Views
0 Comments
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]
}
}
}
LeetCode - Hash Divided String - Go abh/lc/3271.go
121 Views
0 Comments
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 {
LeetCode - Two Out of Three - Go abh/lc/2032.go
130 Views
0 Comments
func contain(nums []int, target int) bool {
for _, n := range nums {
if n == target {
return true
}
}
return false
}
LeetCode - Sum of Good Numbers - Go abh/lc/3452.go
165 Views
0 Comments
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
}
LeetCode - Sum of Values at Indices With K Set Bits - Go abh/lc/2859.go
124 Views
0 Comments
func count_set_bit(n int) int {
var count int
for ;n>0; {
if n % 2 == 1 {
n--
count++
}
n /= 2
LeetCode - Word Pattern - Go abh/lc/290.go
125 Views
0 Comments
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])
LeetCode - Merge Strings Alternately - Go abh/lc/1768.go
160 Views
0 Comments
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])
}

LeetCode - Find the Number of Good Pairs - Go abh/lc/3162.go
130 Views
0 Comments
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++
}
}
LeetCode - Move Zeros - Go abh/lc/283.go
124 Views
0 Comments
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]
}
LeetCode - Check If Digits Are Equal in String After Operations I - Go abh/lc/3461.go
138 Views
0 Comments
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
LeetCode - Defanging an IP Address - Go abh/lc/1108.go
138 Views
0 Comments
func defangIPaddr(address string) string {
var defanged string
for _, c := range address {
if c == '.' {
defanged += "[.]"
} else {
defanged += string(c)
}
LeetCode - Find Pivot Index - Go abh/lc/724.go
120 Views
0 Comments
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 {
LeetCode - Find the Difference of Two Arrays - Go abh/lc/2215.go
146 Views
0 Comments
func contain(target int, array []int) bool {
for _, item := range array {
if item == target {
return true
}
}
return false
}
LeetCode - Unique Number of Occurrences - Go abh/lc/1207.go
140 Views
0 Comments
func contain(target int, array []int) bool {
for _, v := range array {
if v == target {
return true
}
}
return false
}
LeetCode - Guess Number Higher or Lower - Go abh/lc/374.go
137 Views
0 Comments
/**
* 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;
*/
LeetCode - Root Equals Sum of Children - Go abh/lc/2236.go
136 Views
0 Comments
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
LeetCode - Transform Array by Parity - Go abh/lc/3467.go
117 Views
0 Comments
func transformArray(nums []int) []int {
o, e := 0, 0
for _, n := range nums {
if n%2==1 {
o++
} else {
e++
}
LeetCode - Spacial Array I - Go abh/lc/3151.go
117 Views
0 Comments
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
LeetCode - Check if a String Is an Acronym of Words - Go abh/lc/2828.go
120 Views
0 Comments
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
}
LeetCode - Count Total Number of Colored Cells - Go abh/lc/2579.go
118 Views
0 Comments
func coloredCells(n int) int64 {
var ans int
for i:=1; i<=n; i++ {
if i == 1 {
ans += 1
} else {
ans += 4*(i)-4
}
LeetCode - Faulty Keyboard - Go abh/lc/2810.go
139 Views
0 Comments
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 {
LeetCode - Minimum Recolors to Get K Consecutive Black Blocks - Go abh/lc/2379.go
137 Views
0 Comments
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++
}
LeetCode - Strictly Palindromic Number - Go abh/lc/2396.go
126 Views
0 Comments
func isStrictlyPalindromic(n int) bool {
return false
}
LeetCode - Find Missing and Repeated Values - Go abh/lc/2965.go
123 Views
0 Comments
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]
}
}
}
LeetCode - Number of Employees Who Met the Target - Go abh/lc/2798.go
150 Views
0 Comments
func numberOfEmployeesWhoMetTarget(hours []int, target int) int {
var ans int
for _, hour := range hours {
if hour >= target {
ans++
}
}
return ans
LeetCode - Find the Largest Almost Missing Integer - Go abh/lc/3471.go
194 Views
0 Comments
func contain(target int, array []int) bool {
for _, v := range array {
if v == target {
return true
}
}
return false
}
LeetCode - Maximum Strong Pair XOR I - Go abh/lc/2932.go
121 Views
0 Comments
func abs(n int) int {
if n < 0 {
return n*-1
}
return n
}
func maximumStrongPairXor(nums []int) int {
var ans int
LeetCode - Contains Duplicate II - Go abh/lc/219.go
120 Views
0 Comments
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
}
}
}
LeetCode - Longest Strictly Increasing or Strictly Decreasing Subarray - Go abh/lc/3105.go
126 Views
0 Comments
func longestMonotonicSubarray(nums []int) int {
l := 0

le := 0
ci := 0
for _, v := range nums {
if v > le {
ci++
LeetCode - Search Insert Position - Go abh/lc/35.go
138 Views
1 Comments
func searchInsert(nums []int, target int) int {
for i, v := range nums {
if target <= v {
return i
}
}
return len(nums)
}
LeetCode - Intersection of Two Arrays - Go abh/lc/349.go
130 Views
0 Comments
func contain(target int, arr []int) bool {
for _, v := range arr {
if v == target {
return true
}
}
return false
}
LeetCode - Maximum Value of a String in an Array - Go abh/lc/2496.go
153 Views
0 Comments
func tpow(x int) int {
p := 1
for ;x>1; x-- {
p *= 10
}
return p
}
func maximumValue(strs []string) int {
LeetCode - Unique Morse Code Words - Go abh/lc/804.go
112 Views
0 Comments
func char_to_morse(char rune) string {
codes := []string{
".-","-...","-.-.","-..",".","..-.","--.",
"....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."}
return codes[char - 97]
}
LeetCode - Maximum Sum of an Hourglass - Go abh/lc/2428.go
147 Views
0 Comments
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 {
LeetCode - Apply Discount Every n Orders - Go abh/lc/1357.go
114 Views
0 Comments
type Cashier struct {
customers_done int
n int
discount int
products []int
prices []int
}

LeetCode - Number of Lines To Write String - Go abh/lc/806.go
112 Views
0 Comments
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
LeetCode - Divide Array Into Equal Pairs - Go abh/lc/2206.go
134 Views
0 Comments
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
LeetCode - Set Mismatch - Go abh/lc/645.go
134 Views
0 Comments
func count(target int, arr []int) int {
var count int
for _, n := range arr {
if n == target {
count++
}
}
return count
LeetCode - Remove Outermost Parentheses - Go abh/lc/1021.go
135 Views
0 Comments
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]
LeetCode - Binary Tree Preorder Traversal - Go abh/lc/144.go
97 Views
0 Comments
https://leetcode.com/problems/binary-tree-preorder-traversal/submissions/1579203892/?envType=problem-list-v2&envId=stack
LeetCode - Reverse Prefix of Word - Go abh/lc/2000.go
121 Views
0 Comments
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])
LeetCode - Remove All Adjacent Duplicates In String - Go abh/lc/1047.go
122 Views
0 Comments
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)
}
LeetCode - Make The String Great - Go abh/lc/1544.go
112 Views
0 Comments
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
func makeGood(s string) string {
var stack []rune
LeetCode - Binary Tree Inorder Traversal - Go abh/lc/94.go
137 Views
0 Comments
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
LeetCode - Number of Students Unable to Eat Lunch - Go abh/lc/1700.go
114 Views
0 Comments
func all_same(arr []int) bool {
for _, v := range arr {
if v != arr[0] {
return false
}
}
return true
}
LeetCode - Baseball Game - Go abh/lc/682.go
116 Views
0 Comments
import "fmt"
type Stack struct {
values []int
}
func (stack *Stack) push(n int) {
stack.values = append(stack.values, n)
}
func (stack *Stack) pop() {
LeetCode - Binary Tree Postorder Traversal - Go abh/lc/145.go
113 Views
0 Comments
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
LeetCode - Crawler Log Folder - Go abh/lc/1598.go
107 Views
0 Comments
func minOperations(logs []string) int {
depth := 0
for _, o := range logs {
if o == "../" {
if depth > 0 {
depth--
}
continue
LeetCode - Maximum Nesting Depth of the Parentheses - Go abh/lc/1614.go
121 Views
0 Comments
func maxDepth(s string) int {
var depth, max_depth int
for _, c := range s {
if c == '(' {
depth++
}
if c == ')' {
depth--
LeetCode - Implement Stack using Queues - Go abh/lc/225.go
138 Views
0 Comments
type MyStack struct {
values []int
len int
}


func Constructor() MyStack {
var stack MyStack
LeetCode - Implement Queue using Stacks - Go abh/lc/232.go
120 Views
0 Comments
// Stack implimentatin
type MyStack struct {
values []int
len int
}

func (this *MyStack) Push(x int) {
this.values = append(this.values, x)
LeetCode - Palindrome Linked List - Go abh/lc/234.go
122 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/

LeetCode - N-ary Tree Preorder Traversal - Go abh/lc/589.go
120 Views
0 Comments
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/

LeetCode - N-ary Tree Postorder Traversal - Go abh/lc/590.go
116 Views
0 Comments
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/

LeetCode - Next Greater Element I - Go abh/lc/496.go
114 Views
0 Comments
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
LeetCode - Richest Customer Wealth - Go abh/lc/1672.go
121 Views
0 Comments
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 {
LeetCode - Number of Recent Calls - Go abh/lc/933.go
137 Views
0 Comments
type RecentCounter struct {
pings []int
}


func Constructor() RecentCounter {
var rc RecentCounter
return rc
LeetCode - Design Parking System - Go abh/lc/1603.go
110 Views
0 Comments
type ParkingSystem struct {
big int
medium int
small int
}


func Constructor(big int, medium int, small int) ParkingSystem {
LeetCode - Number of Valid Words in a Sentence - Go abh/lc/2047.go
114 Views
0 Comments
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
LeetCode - Number of Unequal Triplets in Array - Go abh/lc/2475.go
120 Views
0 Comments
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] &&
LeetCode - Convert Binary Number in a Linked List to Integer - Go abh/lc/1290.go
113 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getDecimalValue(head *ListNode) int {
LeetCode - Middle of the Linked List - Go abh/lc/876.go
122 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func middleNode(head *ListNode) *ListNode {
LeetCode - Rotate List - Go abh/lc/61.go
101 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
Leetcode - Remove Duplicates from Sorted List - Dart abh/lc/83.dart
125 Views
1 Comments
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode? next;
* ListNode([this.val = 0, this.next]);
* }
*/
LeetCode - Robot Bounded In Circle - Dart abh/lc/1041.dart
98 Views
0 Comments
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];
LeetCode - Sqrt(x) - Go abh/lc/69.go
109 Views
0 Comments
func mySqrt(x int) int {
for n := range x+1 {
if n*n >= x || (n+1)*(n+1) > x {
return n
}
}
return 0
}
LeetCode - Excel Sheet Column Number - Go abh/lc/171.go
102 Views
0 Comments
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
}
LeetCode - Longest Substring Without Repeating Characters - Go abh/lc/3.go
97 Views
0 Comments
func contain_duplicate(s string) bool {
for _, c := range s {
var count int
for _, cc := range s {
if c == cc {
count++
}
}
LeetCode - Check if Numbers Are Ascending in a Sentence - Go abh/lc/2042.go
97 Views
0 Comments
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 {
LeetCode - Reverse Linked List - Go abh/lc/206.go
108 Views
0 Comments
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
LeetCode - Remove Nth Node From End of List - Ruby abh/lc/19.rb
113 Views
0 Comments
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
LeetCode - Remove Linked List Elements - Go abh/lc/203.go
93 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeElements(head *ListNode, val int) *ListNode {
LeetCode - Linked List Cycle - Go abh/lc/141.go
106 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/

LeetCode - Linked List Cycle - Ruby abh/lc/141.rb
107 Views
0 Comments
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
LeetCode - Double a Number Represented as a Linked List - Go abh/lc/2816.go
97 Views
0 Comments
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
LeetCode - Delete Node in a Linked List - Go abh/lc/237.go
107 Views
0 Comments
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
LeetCode - Design Linked List - Go abh/lc/707.go
119 Views
0 Comments
// LinkedList //
import "fmt"
// type ListNode struct {
// Val int
// Next *ListNode
// }

type MyLinkedList struct {
LeetCode - Add Two Numbers II - Go abh/lc/445.go
117 Views
0 Comments
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
LeetCode - Next Greater Node In Linked List - Go abh/lc/1019.go
114 Views
0 Comments
// @leet start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
LeetCode - Design Browser History - Go abh/lc/1472.go
111 Views
0 Comments
// @leet start

type BrowserHistoryNode struct {
Url string
Back *BrowserHistoryNode
Forward *BrowserHistoryNode
}

LeetCode - Valid Perfect Square - Go abh/lc/367.go
129 Views
0 Comments
func isPerfectSquare(num int) bool {
n := 1
for {
s := n * n
if s == num {
return true
}
if s > num {
LeetCode - Semi-Ordered Permutation - Go abh/lc/2717.go
91 Views
0 Comments
func SliceFind(arr []int, target int) int {
for i, v := range arr {
if v == target {
return i
}
}
return -1
}
LeetCode - Get Maximum in Generated Array - Go abh/lc/1656.go
107 Views
0 Comments
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
LeetCode - Intersection of Two Linked Lists - Go abh/lc/160.go
114 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/

LeetCode - Minimum Pair Removal to Sort Array I - Go abh/lc/3507.go
119 Views
0 Comments
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
LeetCode - Path Sum - Go abh/lc/112.go
97 Views
0 Comments
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
LeetCode - Find the Array Concatenation Value - Go abh/lc/2562.go
100 Views
0 Comments
class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
n = 0
while nums:
f = nums.pop(0)
if nums:
l = nums.pop()
else:
LeetCode - Swapping Nodes in a Linked List - Go abh/lc/1721.go
105 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/

LeetCode - Flatten a Multilevel Doubly Linked List - Go abh/lc/430.go
109 Views
0 Comments
/**
* Definition for a Node.
* type Node struct {
* Val int
* Prev *Node
* Next *Node
* Child *Node
* }
LeetCode - Minimum Index Sum of Two Lists - Python abh/lc/599.py
96 Views
0 Comments
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)
LeetCode - Design a Text Editor - Go abh/lc/2296.go
103 Views
0 Comments
type Char struct {
Value string
Prev *Char
Next *Char
}

type TextEditor struct {
Cursor *Char
LeetCode - Delete the Middle Node of a Linked List - Go abh/lc/2095.go
127 Views
0 Comments
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/

LeetCode - Find Elements in a Contaminated Binary Tree - Python abh/lc/1261.py
95 Views
0 Comments
# @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:
LeetCode - Find Duplicate File in System - Python abh/lc/609.py
121 Views
0 Comments
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]
LeetCode - Jewels and Stones - Go abh/lc/771.go
122 Views
0 Comments
func numJewelsInStones(jewels string, stones string) int {
var count int
for _, j := range jewels {
for _, s := range stones {
if j == s {
count++
}
}
LeetCode - Keyboard Row - Python abh/lc/500.py
127 Views
0 Comments
class Solution:
def findWords(self, words: List[str]) -> List[str]:
rows = [
"qwertyuiop",
"asdfghjkl",
"zxcvbnm",
]
ans = []
LeetCode - Verifying an Alien Dictionary - Python abh/lc/953.py
125 Views
0 Comments
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:
LeetCode - Check if the Sentence Is Pangram - Python abh/lc/1832.py
136 Views
0 Comments
class Solution:
def checkIfPangram(self, sentence: str) -> bool:
return len(set(sentence)) == 26
LeetCode - Count Good Triplets - Ruby abh/lc/1150.rb
122 Views
0 Comments
# @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
LeetCode - License Key Formatting - Python abh/lc/482.py
111 Views
0 Comments
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:
LeetCode - Check if One String Swap Can Make Strings Equal - Python abh/lc/1790.py
107 Views
0 Comments
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
LeetCode - Last Stone Weight - Python abh/lc/1046.py
100 Views
0 Comments
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:
LeetCode - Flipping an Image - Python abh/lc/832.py
84 Views
0 Comments
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
LeetCode - Last Substring in Lexicographical Order - Python abh/lc/1163.py
81 Views
0 Comments
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
LeetCode - Minimum Number of Operations to Make Elements in Array Distinct - Python abh/lc/3396.py
91 Views
0 Comments
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)
LeetCode - Element Appearing More Than 25% In Sorted Array - Python abh/lc/1287.py
78 Views
0 Comments
class Solution:
def findSpecialInteger(self, arr: List[int]) -> int:
l = len(arr)
t = l / 4
freq = {}
for n in arr:
if n not in freq.keys():
freq[n] = 0