├── .gitattributes ├── .github └── workflows │ └── update-readme.yml ├── .gitignore ├── Java ├── 1-bit and 2-bit Characters.java ├── Add Two Numbers.java ├── Bitwise AND of Numbers Range.java ├── Check If All 1's Are at Least Length K Places Away.java ├── Check if Binary String Has at Most One Segment of Ones.java ├── Check if the Sentence Is Pangram.java ├── Container With Most Water.java ├── Contains Duplicate II.java ├── Contains Duplicate.java ├── Continuous Subarray Sum.java ├── Convert 1D Array Into 2D Array.java ├── Count Binary Substrings.java ├── Count Number of Distinct Integers After Reverse Operations.java ├── Delete Node in a Linked List.java ├── Distribute Candies.java ├── Edit Distance.java ├── Elimination Game.java ├── Find Greatest Common Divisor of Array.java ├── Find Original Array From Doubled Array.java ├── Find The Original Array of Prefix Xor.java ├── Find Winner on a Tic Tac Toe Game.java ├── Find the City With the Smallest Number of Neighbors at a Threshold Distance.java ├── First Bad Version.java ├── First Letter to Appear Twice.java ├── Fizz Buzz.java ├── Generate Parentheses.java ├── Gray Code.java ├── Increasing Triplet Subsequence.java ├── Invert Binary Tree.java ├── Island Perimeter.java ├── Largest Perimeter Triangle.java ├── Lemonade Change.java ├── Linked List Cycle.java ├── Long Pressed Name.java ├── Longest Nice Subarray.java ├── Longest Subarray of 1's After Deleting One Element.java ├── Longest Substring Without Repeating Characters.java ├── Maximum Subarray.java ├── Merge Sorted Array.java ├── Middle of the Linked List.java ├── Minimum Add to Make Parentheses Valid.java ├── Minimum Bit Flips to Convert Number.java ├── Minimum Cost to Make Array Equal.java ├── Minimum Depth of Binary Tree.java ├── Minimum Hours of Training to Win a Competition.java ├── Minimum Number of Vertices to Reach All Nodes.java ├── Minimum Size Subarray Sum.java ├── Most Frequent Even Element.java ├── Move Pieces to Obtain a String.java ├── Nim Game.java ├── Number of Islands.java ├── Number of Subarrays With GCD Equal to K.java ├── Optimal Partition of String.java ├── Pairs of Songs With Total Durations Divisible by 60.java ├── Palindrome Number.java ├── Partition Array Such That Maximum Difference Is K.java ├── Percentage of Letter in String.java ├── Positions of Large Groups.java ├── Pseudo-Palindromic Paths in a Binary Tree.java ├── Range Addition II.java ├── Ransom Note.java ├── Remove Duplicates from Sorted Array.java ├── Remove Element.java ├── Remove Nth Node From End of List.java ├── Remove Palindromic Subsequences.java ├── Reverse Bits.java ├── Reverse Words in a String III.java ├── Richest Customer Wealth.java ├── Rotate Array.java ├── Search a 2D Matrix.java ├── Shuffle the Array.java ├── Single Number.java ├── Smallest Even Multiple.java ├── Stone Game.java ├── Student Attendance Record I.java ├── Substrings of Size Three with Distinct Characters.java ├── Sum of Even Numbers After Queries.java ├── Swap Adjacent in LR String.java ├── Transpose Matrix.java ├── Two Furthest Houses With Different Colors.java ├── Two Sum.java ├── Unique Paths.java ├── Valid Palindrome.java ├── Valid Parentheses.java └── Valid Sudoku.java ├── LICENSE ├── Python ├── 1-bit and 2-bit Characters.py ├── 3Sum With Multiplicity.py ├── 3Sum.py ├── Add Digits.py ├── Add One Row to Tree.py ├── Add Two Numbers.py ├── Add to Array-Form of Integer.py ├── All Paths From Source to Target.py ├── All Possible Full Binary Trees.py ├── Array Nesting.py ├── Array of Doubled Pairs.py ├── As Far from Land as Possible.py ├── Available Captures for Rook.py ├── Average Value of Even Numbers That Are Divisible by Three.py ├── Average of Levels in Binary Tree.py ├── Backspace String Compare.py ├── Bag of Tokens.py ├── Best Poker Hand.py ├── Binary Search.py ├── Binary Subarrays With Sum.py ├── Binary Tree Inorder Traversal.py ├── Binary Tree Maximum Path Sum.py ├── Binary Tree Pruning.py ├── Binary Trees With Factors.py ├── Bitwise AND of Numbers Range.py ├── Break a Palindrome.py ├── Calculate Digit Sum of a String.py ├── Categorize Box According to Criteria.py ├── Check Distances Between Same Letters.py ├── Check If All 1's Are at Least Length K Places Away.py ├── Check If Two String Arrays are Equivalent.py ├── Check if Array Is Sorted and Rotated.py ├── Check if Binary String Has at Most One Segment of Ones.py ├── Check if the Sentence Is Pangram.py ├── Circular Sentence.py ├── Climbing Stairs.py ├── Clumsy Factorial.py ├── Combination Sum IV.py ├── Compare Version Numbers.py ├── Concatenation of Consecutive Binary Numbers.py ├── Construct String from Binary Tree.py ├── Container With Most Water.py ├── Contains Duplicate II.py ├── Contains Duplicate.py ├── Continuous Subarray Sum.py ├── Convert 1D Array Into 2D Array.py ├── Convert Sorted Array to Binary Search Tree.py ├── Convert Sorted List to Binary Search Tree.py ├── Count Asterisks.py ├── Count Binary Substrings.py ├── Count Complete Tree Nodes.py ├── Count Days Spent Together.py ├── Count Distinct Numbers on Board.py ├── Count Good Nodes in Binary Tree.py ├── Count Number of Bad Pairs.py ├── Count Number of Distinct Integers After Reverse Operations.py ├── Count Odd Numbers in an Interval Range.py ├── Count Pairs Of Similar Strings.py ├── Count Prefixes of a Given String.py ├── Count Sub Islands.py ├── Count Unreachable Pairs of Nodes in an Undirected Graph.py ├── Count Vowels Permutation.py ├── Count and Say.py ├── Count the Number of Consistent Strings.py ├── Count the Number of Fair Pairs.py ├── Counting Words With a Given Prefix.py ├── Course Schedule.py ├── Custom Sort String.py ├── Decode Ways.py ├── Delete Columns to Make Sorted.py ├── Delete Node in a Linked List.py ├── Delete the Middle Node of a Linked List.py ├── Design Browser History.py ├── Design Circular Queue.py ├── Design a Stack With Increment Operation.py ├── Detect Capital.py ├── Determine if Two Events Have Conflict.py ├── Determine if Two Strings Are Close.py ├── Diameter of Binary Tree.py ├── Difference Between Ones and Zeros in Row and Column.py ├── Distance Between Bus Stops.py ├── Distribute Candies.py ├── Divide Intervals Into Minimum Number of Groups.py ├── Divide Players Into Teams of Equal Skill.py ├── Earliest Possible Day of Full Bloom.py ├── Edit Distance.py ├── Elimination Game.py ├── Equal Row and Column Pairs.py ├── Evaluate Boolean Binary Tree.py ├── Evaluate Reverse Polish Notation.py ├── Excel Sheet Column Title.py ├── Factorial Trailing Zeroes.py ├── Find Closest Node to Given Two Nodes.py ├── Find Duplicate File in System.py ├── Find Eventual Safe States.py ├── Find Greatest Common Divisor of Array.py ├── Find K Closest Elements.py ├── Find Original Array From Doubled Array.py ├── Find Players With Zero or One Losses.py ├── Find Positive Integer Solution for a Given Equation.py ├── Find Resultant Array After Removing Anagrams.py ├── Find Subarrays With Equal Sum.py ├── Find The Original Array of Prefix Xor.py ├── Find Winner on a Tic Tac Toe Game.py ├── Find and Replace Pattern.py ├── Find the City With the Smallest Number of Neighbors at a Threshold Distance.py ├── Find the K-Beauty of a Number.py ├── Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.py ├── Find the Pivot Integer.py ├── Find the Town Judge.py ├── Finding the Users Active Minutes.py ├── First Bad Version.py ├── First Letter to Appear Twice.py ├── First Unique Character in a String.py ├── Fizz Buzz.py ├── Flatten Binary Tree to Linked List.py ├── Flip String to Monotone Increasing.py ├── Flood Fill.py ├── Fraction Addition and Subtraction.py ├── Fruit Into Baskets.py ├── Generate Parentheses.py ├── Get Maximum in Generated Array.py ├── Gray Code.py ├── Greatest Common Divisor of Strings.py ├── Greatest English Letter in Upper and Lower Case.py ├── Group Anagrams.py ├── Groups of Special-Equivalent Strings.py ├── Guess Number Higher or Lower.py ├── House Robber.py ├── Image Overlap.py ├── Increasing Triplet Subsequence.py ├── Integer to Roman.py ├── Interval List Intersections.py ├── Invert Binary Tree.py ├── Island Perimeter.py ├── Jump Game III.py ├── Jump Game IV.py ├── Jump Game.py ├── Keys and Rooms.py ├── Koko Eating Bananas.py ├── Kth Missing Positive Number.py ├── Largest 3-Same-Digit Number in String.py ├── Largest Local Values in a Matrix.py ├── Largest Number At Least Twice of Others.py ├── Largest Odd Number in String.py ├── Largest Palindromic Number.py ├── Largest Perimeter Triangle.py ├── Largest Positive Integer That Exists With Its Negative.py ├── Leaf-Similar Trees.py ├── Left and Right Sum Differences.py ├── Lemonade Change.py ├── Length of the Longest Alphabetical Continuous Substring.py ├── Linked List Cycle.py ├── Long Pressed Name.py ├── Longer Contiguous Segments of Ones than Zeros.py ├── Longest Common Prefix.py ├── Longest Common Subsequence.py ├── Longest Increasing Path in a Matrix.py ├── Longest Increasing Subsequence.py ├── Longest Nice Subarray.py ├── Longest Palindrome by Concatenating Two Letter Words.py ├── Longest Repeating Character Replacement.py ├── Longest Square Streak in an Array.py ├── Longest String Chain.py ├── Longest Subarray With Maximum Bitwise AND.py ├── Longest Subarray of 1's After Deleting One Element.py ├── Longest Subsequence With Limited Sum.py ├── Longest Substring Of All Vowels in Order.py ├── Longest Substring Without Repeating Characters.py ├── Longest Uploaded Prefix.py ├── Lowest Common Ancestor of a Binary Search Tree.py ├── Make Array Zero by Subtracting Equal Amounts.py ├── Make The String Great.py ├── Matrix Cells in Distance Order.py ├── Max Area of Island.py ├── Maximum 69 Number.py ├── Maximum Average Subarray I.py ├── Maximum Bags With Full Capacity of Rocks.py ├── Maximum Binary Tree II.py ├── Maximum Count of Positive Integer and Negative Integer.py ├── Maximum Depth of Binary Tree.py ├── Maximum Difference Between Node and Ancestor.py ├── Maximum Frequency Stack.py ├── Maximum Ice Cream Bars.py ├── Maximum Length of Repeated Subarray.py ├── Maximum Length of a Concatenated String with Unique Characters.py ├── Maximum Number of Pairs in Array.py ├── Maximum Performance of a Team.py ├── Maximum Points You Can Obtain from Cards.py ├── Maximum Score from Performing Multiplication Operations.py ├── Maximum Subarray.py ├── Maximum Sum of an Hourglass.py ├── Maximum of Absolute Value Expression.py ├── Merge In Between Linked Lists.py ├── Merge Similar Items.py ├── Merge Sorted Array.py ├── Middle of the Linked List.py ├── Min Stack.py ├── Minimum Add to Make Parentheses Valid.py ├── Minimum Amount of Time to Collect Garbage.py ├── Minimum Amount of Time to Fill Cups.py ├── Minimum Bit Flips to Convert Number.py ├── Minimum Cost to Make Array Equal.py ├── Minimum Depth of Binary Tree.py ├── Minimum Difference Between Highest and Lowest of K Scores.py ├── Minimum Distance to the Target Element.py ├── Minimum Domino Rotations For Equal Row.py ├── Minimum Falling Path Sum.py ├── Minimum Genetic Mutation.py ├── Minimum Hours of Training to Win a Competition.py ├── Minimum Number of Arrows to Burst Balloons.py ├── Minimum Number of Refueling Stops.py ├── Minimum Number of Steps to Make Two Strings Anagram II.py ├── Minimum Number of Steps to Make Two Strings Anagram.py ├── Minimum Number of Vertices to Reach All Nodes.py ├── Minimum Recolors to Get K Consecutive Black Blocks.py ├── Minimum Remove to Make Valid Parentheses.py ├── Minimum Rounds to Complete All Tasks.py ├── Minimum Score Triangulation of Polygon.py ├── Minimum Size Subarray Sum.py ├── Minimum Time to Make Rope Colorful.py ├── Monotonic Array.py ├── Most Frequent Even Element.py ├── Most Frequent Subtree Sum.py ├── Move Pieces to Obtain a String.py ├── Move Zeroes.py ├── N-ary Tree Level Order Traversal.py ├── N-th Tribonacci Number.py ├── Nearest Exit from Entrance in Maze.py ├── Nim Game.py ├── Node With Highest Edge Score.py ├── Non-decreasing Subsequences.py ├── Number of 1 Bits.py ├── Number of Arithmetic Triplets.py ├── Number of Closed Islands.py ├── Number of Common Factors.py ├── Number of Dice Rolls With Target Sum.py ├── Number of Enclaves.py ├── Number of Islands.py ├── Number of Operations to Make Network Connected.py ├── Number of Provinces.py ├── Number of Steps to Reduce a Number to Zero.py ├── Number of Subarrays With GCD Equal to K.py ├── Number of Substrings With Only 1s.py ├── Number of Zero-Filled Subarrays.py ├── Numbers With Same Consecutive Differences.py ├── Open the Lock.py ├── Optimal Partition of String.py ├── Pacific Atlantic Water Flow.py ├── Pairs of Songs With Total Durations Divisible by 60.py ├── Palindrome Linked List.py ├── Palindrome Number.py ├── Palindrome Pairs.py ├── Partition Array Such That Maximum Difference Is K.py ├── Partition List.py ├── Partition String Into Substrings With Values at Most K.py ├── Path Crossing.py ├── Path In Zigzag Labelled Binary Tree.py ├── Path Sum II.py ├── Path Sum.py ├── Percentage of Letter in String.py ├── Perfect Squares.py ├── Positions of Large Groups.py ├── Possible Bipartition.py ├── Pow(x, n).py ├── Power of Four.py ├── Power of Three.py ├── Print in Order.py ├── Pseudo-Palindromic Paths in a Binary Tree.py ├── Push Dominoes.py ├── Random Point in Non-overlapping Rectangles.py ├── Range Addition II.py ├── Range Sum Query - Mutable.py ├── Range Sum Query 2D - Immutable.py ├── Range Sum of BST.py ├── Rank Transform of an Array.py ├── Ransom Note.py ├── Rectangle Area.py ├── Rectangle Overlap.py ├── Reduce Array Size to The Half.py ├── Regions Cut By Slashes.py ├── Regular Expression Matching.py ├── Relative Ranks.py ├── Remove All Adjacent Duplicates In String.py ├── Remove Duplicates from Sorted Array II.py ├── Remove Duplicates from Sorted Array.py ├── Remove Duplicates from Sorted List II.py ├── Remove Element.py ├── Remove Nodes From Linked List.py ├── Remove Nth Node From End of List.py ├── Remove Palindromic Subsequences.py ├── Remove Stones to Minimize the Total.py ├── Removing Stars From a String.py ├── Reorder Routes to Make All Paths Lead to the City Zero.py ├── Reordered Power of 2.py ├── Replace All ?'s to Avoid Consecutive Repeating Characters.py ├── Reverse Bits.py ├── Reverse Linked List.py ├── Reverse Vowels of a String.py ├── Reverse Words in a String III.py ├── Reverse Words in a String.py ├── Richest Customer Wealth.py ├── Roman to Integer.py ├── Rotate Array.py ├── Rotate Image.py ├── Rotate List.py ├── Rotated Digits.py ├── Running Sum of 1d Array.py ├── Same Tree.py ├── Satisfiability of Equality Equations.py ├── Search a 2D Matrix.py ├── Search in a Binary Search Tree.py ├── Serialize and Deserialize Binary Tree.py ├── Set Matrix Zeroes.py ├── Set Mismatch.py ├── Shift 2D Grid.py ├── Shortest Completing Word.py ├── Shortest Path Visiting All Nodes.py ├── Shortest Path in Binary Matrix.py ├── Shuffle the Array.py ├── Simplify Path.py ├── Single Number.py ├── Smallest Even Multiple.py ├── Smallest Number in Infinite Set.py ├── Smallest String Starting From Leaf.py ├── Smallest String With A Given Numeric Value.py ├── Sort Integers by The Power Value.py ├── Sort the Matrix Diagonally.py ├── Sort the People.py ├── Spiral Matrix.py ├── Split Array into Consecutive Subsequences.py ├── Squares of a Sorted Array.py ├── Stamping The Sequence.py ├── Stone Game.py ├── Strictly Palindromic Number.py ├── String Compression.py ├── String Matching in an Array.py ├── String to Integer (atoi).py ├── Strong Password Checker II.py ├── Student Attendance Record I.py ├── Subarray Sum Equals K.py ├── Subdomain Visit Count.py ├── Subsets.py ├── Substring with Concatenation of All Words.py ├── Substrings of Size Three with Distinct Characters.py ├── Sum Root to Leaf Numbers.py ├── Sum of Digits of String After Convert.py ├── Sum of Even Numbers After Queries.py ├── Swap Adjacent in LR String.py ├── Symmetric Tree.py ├── Target Sum.py ├── Teemo Attacking.py ├── Text Justification.py ├── The Employee That Worked on the Longest Task.py ├── The Number of Weak Characters in the Game.py ├── Time Needed to Inform All Employees.py ├── Time Needed to Rearrange a Binary String.py ├── Toeplitz Matrix.py ├── Top K Frequent Words.py ├── Transpose Matrix.py ├── Trapping Rain Water.py ├── Triples with Bitwise AND Equal To Zero.py ├── Two Furthest Houses With Different Colors.py ├── Two Sum IV - Input is a BST.py ├── Two Sum.py ├── UTF-8 Validation.py ├── Ugly Number.py ├── Unique Binary Search Trees II.py ├── Unique Binary Search Trees.py ├── Unique Morse Code Words.py ├── Unique Number of Occurrences.py ├── Unique Paths III.py ├── Unique Paths.py ├── Valid Anagram.py ├── Valid Palindrome II.py ├── Valid Palindrome.py ├── Valid Parentheses.py ├── Valid Sudoku.py ├── Validate Binary Search Tree.py ├── Validate IP Address.py ├── Validate Stack Sequences.py ├── Water and Jug Problem.py ├── Word Ladder II.py ├── Word Ladder.py ├── Word Pattern.py ├── Word Search.py └── Zigzag Conversion.py ├── README.md ├── SQL ├── Actors and Directors Who Cooperated At Least Three Times.sql ├── Article Views I.sql ├── Bank Account Summary II.sql ├── Big Countries.sql ├── Calculate Special Bonus.sql ├── Capital Gain%Loss.sql ├── Classes More Than 5 Students.sql ├── Combine Two Tables.sql ├── Consecutive Numbers.sql ├── Customer Placing the Largest Number of Orders.sql ├── Customer Who Visited but Did Not Make Any Transactions.sql ├── Customers Who Never Order.sql ├── Daily Leads and Partners.sql ├── Delete Duplicate Emails.sql ├── Department Highest Salary.sql ├── Department Top Three Salaries.sql ├── Duplicate Emails.sql ├── Employees Earning More Than Their Managers.sql ├── Employees With Missing Information.sql ├── Find Customer Referee.sql ├── Find Followers Count.sql ├── Find Total Time Spent by Each Employee.sql ├── Fix Names in a Table.sql ├── Game Play Analysis I.sql ├── Group Sold Products By The Date.sql ├── Market Analysis I.sql ├── Not Boring Movies.sql ├── Nth Highest Salary.sql ├── Patients With a Condition.sql ├── Rank Scores.sql ├── Rearrange Products Table.sql ├── Recyclable and Low Fat Products.sql ├── Reformat Department Table.sql ├── Rising Temperature.sql ├── Sales Analysis III.sql ├── Sales Person.sql ├── Second Highest Salary.sql ├── Swap Salary.sql ├── The Latest Login in 2020.sql ├── Top Travellers.sql ├── Tree Node.sql └── User Activity for the Past 30 Days I.sql ├── Shell ├── Tenth Line.sh ├── Transpose File.sh ├── Valid Phone Numbers.sh └── Word Frequency.sh └── infrastructure ├── __init__.py ├── config.py ├── requirements.txt ├── run.py └── src ├── __init__.py ├── collector.py ├── db ├── __init__.py ├── models.py └── schemas.py ├── formatter.py ├── markdown_table.py ├── parser.py └── resources ├── __init__.py ├── complexity_notations_table.txt ├── number_of_operations_table.txt ├── problem_details_query.graphql ├── problems.db └── template.py /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sql linguist-detectable=true 2 | -------------------------------------------------------------------------------- /Java/1-bit and 2-bit Characters.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public boolean isOneBitCharacter(int[] bits) { 8 | int i = 0, n = bits.length - 1; 9 | 10 | while (i < n) { 11 | i += bits[i] == 1 ? 2 : 1; 12 | } 13 | 14 | return i == n; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java/Bitwise AND of Numbers Range.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(log(n)) 5 | * Memory: O(1) 6 | */ 7 | public int rangeBitwiseAnd(int left, int right) { 8 | int i = 0; 9 | 10 | while (left != right) { 11 | left >>= 1; 12 | right >>= 1; 13 | ++i; 14 | } 15 | 16 | return left << i; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Check If All 1's Are at Least Length K Places Away.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public boolean kLengthApart(int[] nums, int k) { 8 | int count = k; 9 | 10 | for (int bit : nums) { 11 | if (bit == 1) { 12 | if (count < k) 13 | return false; 14 | count = 0; 15 | } else { 16 | count += 1; 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/Check if Binary String Has at Most One Segment of Ones.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public boolean checkOnesSegment(String s) { 8 | return !s.contains("01"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Java/Container With Most Water.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int maxArea(int[] height) { 8 | int maxArea = 0; 9 | int left = 0, right = height.length - 1; 10 | 11 | while (left < right) { 12 | maxArea = Math.max(Math.min(height[left], height[right]) * (right - left), maxArea); 13 | 14 | if (height[left] < height[right]) { 15 | ++left; 16 | } else { 17 | --right; 18 | } 19 | } 20 | 21 | return maxArea; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Contains Duplicate II.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | class Solution { 5 | 6 | /** 7 | * Time: O(n) 8 | * Memory: O(n) 9 | */ 10 | public boolean containsNearbyDuplicate(int[] nums, int k) { 11 | Map map = new HashMap<>(); 12 | 13 | for (int i = 0; i < nums.length; ++i) { 14 | if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) 15 | return true; 16 | map.put(nums[i], i); 17 | } 18 | 19 | return false; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/Contains Duplicate.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | public class Solution { 5 | 6 | /** 7 | * Time: O(n) 8 | * Memory: O(n) 9 | */ 10 | public boolean containsDuplicate(int[] nums) { 11 | Set set = new HashSet(); 12 | 13 | for (int num : nums) 14 | if (!set.add(num)) 15 | return true; 16 | 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/Continuous Subarray Sum.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Solution { 5 | 6 | /** 7 | * Time: O(n) 8 | * Memory: O(n) 9 | */ 10 | public boolean checkSubarraySum(int[] nums, int k) { 11 | Map memo = new HashMap<>(); 12 | memo.put(0, 0); 13 | int s = 0; 14 | 15 | for (int i = 0; i < nums.length; ++i) { 16 | s = (s + nums[i]) % k; 17 | 18 | if (!memo.containsKey(s)) 19 | memo.put(s, i + 1); 20 | else if (memo.get(s) < i) 21 | return true; 22 | } 23 | return false; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Java/Convert 1D Array Into 2D Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n*m) 5 | * Memory: O(1) 6 | */ 7 | public int[][] construct2DArray(int[] original, int m, int n) { 8 | if (original.length != m * n) 9 | return new int[0][0]; 10 | 11 | int[][] result = new int[m][n]; 12 | for (int i = 0; i < original.length; i++) 13 | result[i / n][i % n] = original[i]; 14 | 15 | return result; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Java/Count Binary Substrings.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int countBinarySubstrings(String s) { 8 | int substrings = 0; 9 | int prev = 0, curr = 1; 10 | 11 | for (int i = 1; i < s.length(); ++i) { 12 | if (s.charAt(i - 1) != s.charAt(i)) { 13 | substrings += Math.min(prev, curr); 14 | prev = curr; 15 | curr = 1; 16 | } else { 17 | ++curr; 18 | } 19 | } 20 | 21 | return substrings + Math.min(prev, curr); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Count Number of Distinct Integers After Reverse Operations.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | public class Solution { 4 | 5 | /** 6 | * Time: O(n) 7 | * Memory: O(n) 8 | */ 9 | public int countDistinctIntegers(int[] nums) { 10 | HashSet uniq = new HashSet<>(); 11 | 12 | for (int num : nums) { 13 | uniq.add(num); 14 | int reverse = 0; 15 | 16 | for (; num != 0; num /= 10) 17 | reverse = reverse * 10 + num % 10; 18 | 19 | uniq.add(reverse); 20 | } 21 | 22 | return uniq.size(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/Delete Node in a Linked List.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(1) 5 | * Memory: O(1) 6 | */ 7 | public void deleteNode(ListNode node) { 8 | node.val = node.next.val; 9 | node.next = node.next.next; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Java/Distribute Candies.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | public class Solution { 5 | 6 | /** 7 | * Time: O(n) 8 | * Memory: O(n) 9 | */ 10 | public int distributeCandies(int[] candyType) { 11 | Set uniqueCandiesSet = new HashSet<>(); 12 | 13 | for (int candy : candyType) 14 | uniqueCandiesSet.add(candy); 15 | 16 | return Math.min(uniqueCandiesSet.size(), candyType.length / 2); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Elimination Game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(log(n)) 5 | * Memory: O(log(n)) 6 | */ 7 | public int lastRemaining(int n) { 8 | return n == 1 ? 1 : 2 * (n / 2 + 1 - lastRemaining(n / 2)); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Java/Find The Original Array of Prefix Xor.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int[] findArray(int[] pref) { 8 | for (int i = pref.length - 1; i > 0; --i) 9 | pref[i] ^= pref[i - 1]; 10 | return pref; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Java/First Bad Version.java: -------------------------------------------------------------------------------- 1 | public class Solution extends VersionControl { 2 | 3 | /** 4 | * Time: O(log(n)) 5 | * Memory: O(1) 6 | */ 7 | public int firstBadVersion(int n) { 8 | int left = 0, right = n; 9 | 10 | while (left <= right) { 11 | int mid = left + (right - left) / 2; 12 | if (isBadVersion(mid)) 13 | right = mid - 1; 14 | else 15 | left = mid + 1; 16 | } 17 | 18 | return left; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/Fizz Buzz.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | class Solution { 5 | 6 | /** 7 | * Time: O(n) 8 | * Memory: O(1) 9 | */ 10 | public List fizzBuzz(int n) { 11 | List list = new ArrayList<>(); 12 | 13 | for (int i = 1; i <= n; ++i) { 14 | if (i % 15 == 0) 15 | list.add("FizzBuzz"); 16 | else if (i % 3 == 0) 17 | list.add("Fizz"); 18 | else if (i % 5 == 0) 19 | list.add("Buzz"); 20 | else 21 | list.add(Integer.toString(i)); 22 | } 23 | 24 | return list; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java/Increasing Triplet Subsequence.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public boolean increasingTriplet(int[] nums) { 8 | int firstMin = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE; 9 | 10 | for (int num : nums) { 11 | if (num <= firstMin) { 12 | firstMin = num; 13 | } else if (num <= secondMin) { 14 | secondMin = num; 15 | } else { 16 | return true; 17 | } 18 | } 19 | 20 | return false; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/Invert Binary Tree.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(n) 6 | */ 7 | public TreeNode invertTree(TreeNode root) { 8 | if (root != null) { 9 | TreeNode tmp = root.left; 10 | root.left = invertTree(root.right); 11 | root.right = invertTree(tmp); 12 | } 13 | return root; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Java/Largest Perimeter Triangle.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Solution { 4 | 5 | /** 6 | * Time: O(n*log(n)) 7 | * Memory: O(1) 8 | */ 9 | public int largestPerimeter(int[] A) { 10 | Arrays.sort(A); 11 | 12 | for (int i = A.length - 3; i >= 0; --i) 13 | if (A[i] + A[i + 1] > A[i + 2]) 14 | return A[i] + A[i + 1] + A[i + 2]; 15 | 16 | return 0; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Lemonade Change.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public boolean lemonadeChange(int[] bills) { 8 | int five = 0, ten = 0; 9 | 10 | for (int bill : bills) { 11 | if (bill == 5) { 12 | five += 1; 13 | } else if (bill == 10 && five > 0) { 14 | five -= 1; 15 | ten += 1; 16 | } else if (bill == 20 && ten > 0 && five > 0) { 17 | five -= 1; 18 | ten -= 1; 19 | } else if (bill == 20 && five >= 3) { 20 | five -= 3; 21 | } else { 22 | return false; 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Java/Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public boolean hasCycle(ListNode head) { 8 | ListNode slow = head, fast= head; 9 | 10 | while (fast != null && fast.next != null) { 11 | slow = slow.next; 12 | fast = fast.next; 13 | 14 | if (slow == fast) 15 | return true; 16 | } 17 | 18 | return false; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/Long Pressed Name.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(m) 5 | * Memory: O(1) 6 | */ 7 | public boolean isLongPressedName(String name, String typed) { 8 | int i = 0, n = name.length(), m = typed.length(); 9 | 10 | for (int j = 0; j < m; ++j) 11 | if (i < n && name.charAt(i) == typed.charAt(j)) 12 | ++i; 13 | else if (j == 0 || typed.charAt(j) != typed.charAt(j - 1)) 14 | return false; 15 | 16 | return i == n; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Longest Nice Subarray.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int longestNiceSubarray(int[] nums) { 8 | int longest = 0, used_bits = 0, j = 0; 9 | 10 | for (int i = 0; i < nums.length; ++i) { 11 | while ((used_bits & nums[i]) != 0) 12 | used_bits ^= nums[j++]; 13 | 14 | used_bits |= nums[i]; 15 | longest = Math.max(longest, i - j + 1); 16 | } 17 | 18 | return longest; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/Longest Subarray of 1's After Deleting One Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int longestSubarray(int[] nums) { 8 | int longest = 0; 9 | int prev = 0, curr = 0; 10 | 11 | for (int bit : nums) { 12 | if (bit == 0) { 13 | prev = curr; 14 | curr = 0; 15 | } else { 16 | longest = Math.max(longest, prev + ++curr); 17 | } 18 | } 19 | 20 | return longest == nums.length ? longest - 1 : longest; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/Longest Substring Without Repeating Characters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(n) 6 | */ 7 | public int lengthOfLongestSubstring(String s) { 8 | int[] nextIndex = new int[128]; 9 | int longest = 0, left = 0; 10 | 11 | for (int right = 0; right < s.length(); right++) { 12 | left = Math.max(nextIndex[s.charAt(right)], left); 13 | longest = Math.max(longest, right - left + 1); 14 | nextIndex[s.charAt(right)] = right + 1; 15 | } 16 | 17 | return longest; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public static int maxSubArray(int[] nums) { 8 | int maxSum = nums[0], subarrayStart = nums[0]; 9 | 10 | for (int i = 1; i < nums.length; ++i) { 11 | subarrayStart = Math.max(subarrayStart + nums[i], nums[i]); 12 | maxSum = Math.max(maxSum, subarrayStart); 13 | } 14 | 15 | return maxSum; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Java/Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n + m) 5 | * Memory: O(1) 6 | */ 7 | public void merge(int[] first, int n, int[] second, int m) { 8 | int i = n - 1, j = m - 1; 9 | 10 | for (int curr = n + m - 1; curr >= 0; --curr) 11 | if (j < 0) 12 | first[curr] = first[i--]; 13 | else if (i < 0) 14 | first[curr] = second[j--]; 15 | else if (first[i] > second[j]) 16 | first[curr] = first[i--]; 17 | else 18 | first[curr] = second[j--]; 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/Middle of the Linked List.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public ListNode middleNode(ListNode head) { 8 | ListNode slow = head, fast = head; 9 | 10 | while (fast != null && fast.next != null) { 11 | slow = slow.next; 12 | fast = fast.next.next; 13 | } 14 | 15 | return slow; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Java/Minimum Add to Make Parentheses Valid.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int minAddToMakeValid(String s) { 8 | int add = 0, score = 0; 9 | 10 | for (int i = 0; i < s.length(); ++i) { 11 | score += s.charAt(i) == '(' ? 1 : -1; 12 | if (score == -1) { 13 | ++add; 14 | ++score; 15 | } 16 | } 17 | 18 | return add + score; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java/Minimum Bit Flips to Convert Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(log(n)) 5 | * Memory: O(1) 6 | */ 7 | public int minBitFlips(int start, int goal) { 8 | int diff = start ^ goal, flips = 0; 9 | 10 | for (int i = 0; i < 32; ++i) 11 | if ((diff & (1 << i)) != 0) 12 | flips += 1; 13 | 14 | return flips; 15 | } 16 | } 17 | 18 | public class Solution { 19 | 20 | /** 21 | * Time: O(log(n)) 22 | * Memory: O(1) 23 | */ 24 | public int minBitFlips(int start, int goal) { 25 | return Integer.bitCount(start ^ goal); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/Minimum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(n) 6 | */ 7 | public int minDepth(TreeNode root) { 8 | if (root == null) 9 | return 0; 10 | 11 | int leftDepth = minDepth(root.left), rightDepth = minDepth(root.right); 12 | int min = Math.min(leftDepth, rightDepth); 13 | 14 | return 1 + (min > 0 ? min : Math.max(leftDepth, rightDepth)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java/Minimum Number of Vertices to Reach All Nodes.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Solution { 5 | 6 | /** 7 | * Time: O(n) 8 | * Memory: O(n) 9 | */ 10 | public List findSmallestSetOfVertices(int n, List> edges) { 11 | List res = new ArrayList<>(); 12 | int[] seen = new int[n]; 13 | 14 | for (List e : edges) 15 | seen[e.get(1)] = 1; 16 | 17 | for (int i = 0; i < n; ++i) 18 | if (seen[i] == 0) 19 | res.add(i); 20 | 21 | return res; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Minimum Size Subarray Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int minSubArrayLen(int target, int[] nums) { 8 | int minLen = Integer.MAX_VALUE; 9 | int window_sum = 0, start = 0; 10 | 11 | for (int end = 0; end < nums.length; ++end) { 12 | window_sum += nums[end]; 13 | 14 | while (window_sum >= target) { 15 | minLen = Math.min(minLen, end - start + 1); 16 | window_sum -= nums[start++]; 17 | } 18 | } 19 | 20 | return minLen == Integer.MAX_VALUE ? 0 : minLen; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/Most Frequent Even Element.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | class Solution { 4 | 5 | /** 6 | * Time: O(n) 7 | * Memory: O(n) 8 | */ 9 | public int mostFrequentEven(int[] nums) { 10 | HashMap numFrequency = new HashMap<>(); 11 | int mostFreq = -1, maxFreq = 0; 12 | 13 | for (var n : nums) { 14 | if (n % 2 != 0) 15 | continue; 16 | 17 | int freq = numFrequency.getOrDefault(n, 0) + 1; 18 | numFrequency.put(n, freq); 19 | 20 | if (freq > maxFreq || freq == maxFreq && mostFreq > n) { 21 | mostFreq = n; 22 | maxFreq = freq; 23 | } 24 | } 25 | 26 | return mostFreq; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Java/Nim Game.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(1) 5 | * Memory: O(1) 6 | */ 7 | public boolean canWinNim(int n) { 8 | return n % 4 != 0; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Java/Number of Subarrays With GCD Equal to K.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyrylo-Ktl/LeetCode-Solutions/31e0264f803cdc61da9da6fd3a83109a76d216d5/Java/Number of Subarrays With GCD Equal to K.java -------------------------------------------------------------------------------- /Java/Optimal Partition of String.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | public class Solution { 4 | 5 | /** 6 | * Time: O(n) 7 | * Memory: O(1) 8 | */ 9 | public int partitionString(String s) { 10 | HashSet usedChars = new HashSet<>(); 11 | int numOfPartitions = 0; 12 | 13 | for (int i = 0; i < s.length(); ++i) { 14 | if (usedChars.contains(s.charAt(i))) { 15 | usedChars.clear(); 16 | numOfPartitions += 1; 17 | } 18 | usedChars.add(s.charAt(i)); 19 | } 20 | 21 | return numOfPartitions + 1; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Palindrome Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(log10(n)) 5 | * Memory: O(1) 6 | */ 7 | public boolean isPalindrome(int n) { 8 | if (n < 0 || (n % 10 == 0 && n != 0)) 9 | return false; 10 | 11 | int reverted = 0; 12 | while (n > reverted) { 13 | reverted = reverted * 10 + n % 10; 14 | n /= 10; 15 | } 16 | 17 | return n == reverted || n == reverted / 10; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/Partition Array Such That Maximum Difference Is K.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | 5 | /** 6 | * Time: O(n*log(n)) 7 | * Memory: O(1) 8 | */ 9 | public int partitionArray(int[] nums, int k) { 10 | Arrays.sort(nums); 11 | int partitions = 0; 12 | int start = -100000; 13 | 14 | for (int num : nums) { 15 | if (num - start > k) { 16 | partitions += 1; 17 | start = num; 18 | } 19 | } 20 | 21 | return partitions; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Percentage of Letter in String.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int percentageLetter(String s, char letter) { 8 | int count = 0; 9 | 10 | for (int i = 0; i < s.length(); ++i) 11 | if (s.charAt(i) == letter) 12 | count += 1; 13 | 14 | return count * 100 / s.length(); 15 | } 16 | } 17 | 18 | 19 | public class Solution { 20 | 21 | /** 22 | * Time: O(n) 23 | * Memory: O(1) 24 | */ 25 | public int percentageLetter(String s, char letter) { 26 | return (int) (s.chars().filter(ch -> ch == letter).count() * 100 / s.length()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Java/Pseudo-Palindromic Paths in a Binary Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(n) 6 | */ 7 | public int pseudoPalindromicPaths (TreeNode root) { 8 | return preorder(root, 0); 9 | } 10 | 11 | public int preorder(TreeNode node, int path) { 12 | if (node == null) 13 | return 0; 14 | 15 | path = path ^ (1 << node.val); 16 | if (node.left == null && node.right == null) 17 | if ((path & (path - 1)) == 0) 18 | return 1; 19 | 20 | return preorder(node.left, path) + preorder(node.right, path); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/Range Addition II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int maxCount(int rows, int cols, int[][] ops) { 8 | int minRow = rows; 9 | int minCol = cols; 10 | 11 | for (int[] op : ops) { 12 | minRow = Math.min(minRow, op[0]); 13 | minCol = Math.min(minCol, op[1]); 14 | } 15 | 16 | return minRow * minCol; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Remove Duplicates from Sorted Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int removeDuplicates(int[] nums) { 8 | int pos = 0; 9 | 10 | for (int i = 0; i < nums.length; ++i) 11 | if (i == 0 || nums[i - 1] != nums[i]) { 12 | nums[pos] = nums[i]; 13 | pos += 1; 14 | } 15 | 16 | return pos; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Remove Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int removeElement(int[] nums, int val) { 8 | int i = 0; 9 | 10 | for (int num : nums) 11 | if (num != val) 12 | nums[i++] = num; 13 | 14 | return i; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java/Remove Nth Node From End of List.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public ListNode removeNthFromEnd(ListNode head, int n) { 8 | ListNode fast = head, slow = head; 9 | 10 | for (int k = 0; k < n; ++k) 11 | fast = fast.next; 12 | 13 | if (fast == null) 14 | return head.next; 15 | 16 | while (fast.next != null) { 17 | fast = fast.next; 18 | slow = slow.next; 19 | } 20 | 21 | slow.next = slow.next.next; 22 | 23 | return head; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Java/Remove Palindromic Subsequences.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int removePalindromeSub(String s) { 8 | int n = s.length(); 9 | 10 | for (int i = 0; i < n / 2; ++i) 11 | if (s.charAt(i) != s.charAt(n - 1 - i)) 12 | return 2; 13 | 14 | return 1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java/Reverse Bits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(1) 5 | * Memory: O(1) 6 | */ 7 | public int reverseBits(int num) { 8 | num = ((num & 0xffff0000) >>> 16) | ((num & 0x0000ffff) << 16); 9 | num = ((num & 0xff00ff00) >>> 8) | ((num & 0x00ff00ff) << 8); 10 | num = ((num & 0xf0f0f0f0) >>> 4) | ((num & 0x0f0f0f0f) << 4); 11 | num = ((num & 0xcccccccc) >>> 2) | ((num & 0x33333333) << 2); 12 | num = ((num & 0xaaaaaaaa) >>> 1) | ((num & 0x55555555) << 1); 13 | return num; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Java/Reverse Words in a String III.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(n) 6 | */ 7 | public String reverseWords(String s) { 8 | StringBuilder reversed = new StringBuilder(); 9 | 10 | for (String word : s.split("\\s")) 11 | reversed.append(new StringBuilder(word).reverse()).append(" "); 12 | 13 | return reversed.toString().trim(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Java/Richest Customer Wealth.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Solution { 4 | 5 | /** 6 | * Time: O(n*m) 7 | * Memory: O(1) 8 | */ 9 | public int maximumWealth(int[][] accounts) { 10 | return Arrays.stream(accounts).mapToInt(row -> Arrays.stream(row).sum()).max().getAsInt(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Java/Rotate Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public void rotate(int[] nums, int k) { 8 | int n = nums.length; 9 | k %= n; 10 | reverse(nums, 0, n - 1); 11 | reverse(nums, 0, k - 1); 12 | reverse(nums, k, n - 1); 13 | } 14 | 15 | public void reverse(int[] nums, int start, int end) { 16 | for (; start < end; ++start, --end) { 17 | int temp = nums[start]; 18 | nums[start] = nums[end]; 19 | nums[end] = temp; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/Search a 2D Matrix.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(log(n*m)) 5 | * Memory: O(1) 6 | */ 7 | public boolean searchMatrix(int[][] matrix, int target) { 8 | int n = matrix.length, m = matrix[0].length; 9 | int left = 0, right = n * m - 1; 10 | 11 | while (left <= right) { 12 | int mid = (left + right) / 2; 13 | int num = matrix[mid / m][mid % m]; 14 | 15 | if (num == target) 16 | return true; 17 | 18 | if (num < target) { 19 | left = mid + 1; 20 | } else { 21 | right = mid - 1; 22 | } 23 | } 24 | 25 | return false; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/Shuffle the Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int[] shuffle(int[] nums, int n) { 8 | 9 | int[] ans = new int[2 * n]; 10 | 11 | for (int i = 0; i < n; ++i) { 12 | ans[2 * i] = nums[i]; 13 | ans[2 * i + 1] = nums[i + n]; 14 | } 15 | 16 | return ans; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Single Number.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Solution { 4 | 5 | /** 6 | * Time: O(n) 7 | * Memory: O(1) 8 | */ 9 | public int singleNumber(int[] nums) { 10 | int single = 0; 11 | 12 | for (int num : nums) 13 | single ^= num; 14 | 15 | return single; 16 | } 17 | } 18 | 19 | public class Solution { 20 | 21 | /** 22 | * Time: O(n) 23 | * Memory: O(1) 24 | */ 25 | public int singleNumber(int[] nums) { 26 | return Arrays.stream(nums).reduce(0, (single, num) -> single ^ num); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Java/Smallest Even Multiple.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(1) 5 | * Memory: O(1) 6 | */ 7 | public int smallestEvenMultiple(int n) { 8 | return n << (n & 1); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Java/Stone Game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(1) 5 | * Memory: O(1) 6 | */ 7 | public boolean stoneGame(int[] piles) { 8 | return true; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Java/Student Attendance Record I.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public boolean checkRecord(String s) { 8 | return s.indexOf("A") == s.lastIndexOf("A") && !s.contains("LLL"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Java/Transpose Matrix.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | /** 4 | * Time: O(n*m) 5 | * Memory: O(1) 6 | */ 7 | public int[][] transpose(int[][] A) { 8 | int n = A.length, m = A[0].length; 9 | int[][] transposed = new int[m][n]; 10 | 11 | for (int i = 0; i < n; ++i) 12 | for (int j = 0; j < m; ++j) 13 | transposed[j][i] = A[i][j]; 14 | 15 | return transposed; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Java/Two Furthest Houses With Different Colors.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | /** 4 | * Time: O(n) 5 | * Memory: O(1) 6 | */ 7 | public int maxDistance(int[] colors) { 8 | int maxDist = 0, n = colors.length; 9 | 10 | for (int i = 0; i < n; ++i) { 11 | if (colors[i] != colors[0]) 12 | maxDist = Math.max(maxDist, i); 13 | if (colors[i] != colors[n - 1]) 14 | maxDist = Math.max(maxDist, n - i - 1); 15 | } 16 | 17 | return maxDist; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/Two Sum.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | class Solution { 4 | 5 | /** 6 | * Time: O(n) 7 | * Memory: O(n) 8 | */ 9 | public int[] twoSum(int[] numbers, int target) { 10 | HashMap hash = new HashMap<>(); 11 | 12 | for (int i = 0; i < numbers.length; i++) { 13 | Integer diff = target - numbers[i]; 14 | if (hash.containsKey(diff)) 15 | return new int[]{hash.get(diff), i}; 16 | hash.put(numbers[i], i); 17 | } 18 | 19 | return null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Solution { 4 | 5 | /** 6 | * Time: O(n) 7 | * Memory: O(n) 8 | */ 9 | public boolean isValid(String s) { 10 | Stack stack = new Stack<>(); 11 | 12 | for (char c : s.toCharArray()) { 13 | if (c == '(') 14 | stack.push(')'); 15 | else if (c == '{') 16 | stack.push('}'); 17 | else if (c == '[') 18 | stack.push(']'); 19 | else if (stack.isEmpty() || stack.pop() != c) 20 | return false; 21 | } 22 | 23 | return stack.isEmpty(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Python/1-bit and 2-bit Characters.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def isOneBitCharacter(self, bits: List[int]) -> bool: 11 | i, n = 0, len(bits) - 1 12 | 13 | while i < n: 14 | i += 2 if bits[i] == 1 else 1 15 | 16 | return i == n 17 | -------------------------------------------------------------------------------- /Python/Add Digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | def addDigits(self, num: int) -> int: 8 | return 1 + (num - 1) % 9 if num else 0 9 | -------------------------------------------------------------------------------- /Python/Add to Array-Form of Integer.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(log10(k)) 7 | Memory: O(1) 8 | """ 9 | 10 | BASE = 10 11 | 12 | def addToArrayForm(self, num: List[int], k: int) -> List[int]: 13 | i = len(num) - 1 14 | 15 | while i >= 0 and k: 16 | k, num[i] = divmod(num[i] + k, self.BASE) 17 | i -= 1 18 | 19 | while k: 20 | k, a = divmod(k, self.BASE) 21 | num.insert(0, a) 22 | 23 | return num 24 | -------------------------------------------------------------------------------- /Python/All Paths From Source to Target.py: -------------------------------------------------------------------------------- 1 | from typing import Generator, List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def allPathsSourceTarget(self, graph: List[List[int]]) -> Generator: 11 | def dfs(u: int, t: int, path: List[int]) -> Generator: 12 | if u == t: 13 | yield path 14 | 15 | for v in graph[u]: 16 | yield from dfs(v, t, path + [v]) 17 | 18 | graph = { 19 | u: set(neighbours) 20 | for u, neighbours in enumerate(graph) 21 | } 22 | return dfs(0, len(graph) - 1, [0]) 23 | -------------------------------------------------------------------------------- /Python/Array Nesting.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def arrayNesting(self, nums: List[int]) -> int: 11 | seen = [False] * len(nums) 12 | max_length = 0 13 | 14 | for k in nums: 15 | length = 0 16 | while not seen[k]: 17 | seen[k], length, k = True, length + 1, nums[k] 18 | max_length = max(max_length, length) 19 | 20 | return max_length 21 | -------------------------------------------------------------------------------- /Python/Array of Doubled Pairs.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n + k*log2(k)) 8 | Memory: O(n) 9 | """ 10 | 11 | def canReorderDoubled(self, arr: List[int]) -> bool: 12 | count = Counter(arr) 13 | 14 | for num in sorted(count, key=abs): 15 | if count[num] > count[2 * num]: 16 | return False 17 | count[2 * num] -= count[num] 18 | 19 | return True 20 | -------------------------------------------------------------------------------- /Python/Backspace String Compare.py: -------------------------------------------------------------------------------- 1 | from itertools import zip_longest 2 | from typing import Generator 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(min(n, m)) 8 | Memory: O(1) 9 | """ 10 | 11 | def backspaceCompare(self, s: str, t: str) -> bool: 12 | return not any(a != b for a, b in zip_longest(self._build(s), self._build(t))) 13 | 14 | @staticmethod 15 | def _build(string: str) -> Generator: 16 | skip = 0 17 | for ch in reversed(string): 18 | if ch == '#': 19 | skip += 1 20 | elif skip: 21 | skip -= 1 22 | else: 23 | yield ch 24 | -------------------------------------------------------------------------------- /Python/Bag of Tokens.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log(n)) 7 | Memory: O(1) 8 | """ 9 | 10 | def bagOfTokensScore(self, tokens: List[int], power: int) -> int: 11 | tokens.sort() 12 | i, j = 0, len(tokens) - 1 13 | max_score = score = 0 14 | 15 | while i <= j: 16 | if tokens[i] <= power: 17 | power -= tokens[i] 18 | score += 1 19 | i += 1 20 | max_score = max(max_score, score) 21 | elif score > 0: 22 | power += tokens[j] 23 | score -= 1 24 | j -= 1 25 | else: 26 | break 27 | 28 | return max_score 29 | -------------------------------------------------------------------------------- /Python/Best Poker Hand.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(1) 8 | Memory: O(1) 9 | """ 10 | 11 | def bestHand(self, ranks: List[int], suits: List[str]) -> str: 12 | max_rank_cnt = max(Counter(ranks).values()) 13 | max_suit_cnt = max(Counter(suits).values()) 14 | 15 | return { 16 | max_rank_cnt == 2: 'Pair', 17 | max_rank_cnt >= 3: 'Three of a Kind', 18 | max_suit_cnt == 5: 'Flush', 19 | }.get(True, 'High Card') 20 | -------------------------------------------------------------------------------- /Python/Binary Search.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(log(n)) 7 | Memory: O(1) 8 | """ 9 | 10 | def search(self, nums: List[int], target: int) -> int: 11 | left, right = 0, len(nums) - 1 12 | 13 | while left <= right: 14 | mid = (left + right) // 2 15 | 16 | if nums[mid] == target: 17 | return mid 18 | 19 | if nums[mid] > target: 20 | right = mid - 1 21 | else: 22 | left = mid + 1 23 | 24 | return -1 25 | -------------------------------------------------------------------------------- /Python/Binary Subarrays With Sum.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from itertools import accumulate 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | """ 8 | Time: O(n) 9 | Memory: O(n) 10 | """ 11 | 12 | def numSubarraysWithSum(self, nums: List[int], target: int) -> int: 13 | prefix_sums = defaultdict(int) 14 | prefix_sums[0] = 1 15 | 16 | sub_arrays = 0 17 | for prefix in accumulate(nums): 18 | sub_arrays += prefix_sums[prefix - target] 19 | prefix_sums[prefix] += 1 20 | 21 | return sub_arrays 22 | -------------------------------------------------------------------------------- /Python/Binary Tree Pruning.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, val=0, left=None, right=None): 6 | self.val = val 7 | self.left = left 8 | self.right = right 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(n) 14 | Memory: O(n) 15 | """ 16 | 17 | def pruneTree(self, root: TreeNode) -> TreeNode: 18 | return self._prune(root) 19 | 20 | @classmethod 21 | def _prune(cls, root: Optional[TreeNode]) -> Optional[TreeNode]: 22 | if not root: 23 | return None 24 | 25 | root.left = cls._prune(root.left) 26 | root.right = cls._prune(root.right) 27 | 28 | return root if (root.val or root.left or root.right) else None 29 | -------------------------------------------------------------------------------- /Python/Binary Trees With Factors.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n^2) 7 | Memory: O(n) 8 | """ 9 | 10 | MOD = 10 ** 9 + 7 11 | 12 | def numFactoredBinaryTrees(self, arr: List[int]) -> int: 13 | arr.sort() 14 | dp = {x: 1 for x in arr} 15 | 16 | for i in range(len(arr)): 17 | for j in range(i): 18 | if arr[i] / arr[j] in dp: 19 | dp[arr[i]] += dp[arr[j]] * dp[arr[i] / arr[j]] 20 | 21 | return sum(dp.values()) % self.MOD 22 | -------------------------------------------------------------------------------- /Python/Bitwise AND of Numbers Range.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log(n)) 4 | Memory: O(1) 5 | """ 6 | 7 | def rangeBitwiseAnd(self, left: int, right: int) -> int: 8 | i = 0 9 | 10 | while left != right: 11 | left >>= 1 12 | right >>= 1 13 | i += 1 14 | 15 | return left << i 16 | -------------------------------------------------------------------------------- /Python/Break a Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def breakPalindrome(self, palindrome: str) -> str: 8 | if len(palindrome) == 1: 9 | return '' 10 | 11 | n = len(palindrome) 12 | letters = list(palindrome) 13 | 14 | for i in range(n // 2): 15 | if letters[i] > 'a': 16 | letters[i] = 'a' 17 | break 18 | else: 19 | letters[-1] = 'b' 20 | 21 | return ''.join(letters) 22 | -------------------------------------------------------------------------------- /Python/Categorize Box According to Criteria.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str: 8 | is_bulky = length >= 10_000 or width >= 10_000 or height >= 10_000 or length * width * height >= 1_000_000_000 9 | is_heavy = mass >= 100 10 | 11 | return { 12 | (True, True): 'Both', 13 | (True, False): 'Bulky', 14 | (False, True): 'Heavy', 15 | (False, False): 'Neither', 16 | }[(is_bulky, is_heavy)] 17 | -------------------------------------------------------------------------------- /Python/Check Distances Between Same Letters.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(1) 8 | Memory: O(1) 9 | """ 10 | 11 | def checkDistances(self, s: str, distance: List[int]) -> bool: 12 | d = defaultdict(list) 13 | 14 | for i, ch in enumerate(s): 15 | d[ch].append(i) 16 | 17 | return all(j - i - 1 == distance[ord(ch) - 97] for ch, (i, j) in d.items()) 18 | -------------------------------------------------------------------------------- /Python/Check If All 1's Are at Least Length K Places Away.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def kLengthApart(self, nums: List[int], k: int) -> bool: 11 | count = k 12 | 13 | for bit in nums: 14 | if bit: 15 | if count < k: 16 | return False 17 | count = 0 18 | else: 19 | count += 1 20 | 21 | return True 22 | -------------------------------------------------------------------------------- /Python/Check if Array Is Sorted and Rotated.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def check(self, nums: List[int]) -> bool: 11 | n = len(nums) 12 | 13 | for i in range(1, n): 14 | if nums[i - 1] > nums[i]: 15 | return nums[0] >= nums[-1] and all(nums[j] <= nums[j + 1] for j in range(i, n - 1)) 16 | 17 | return True 18 | -------------------------------------------------------------------------------- /Python/Check if Binary String Has at Most One Segment of Ones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def checkOnesSegment(self, s: str) -> bool: 8 | return '01' not in s 9 | -------------------------------------------------------------------------------- /Python/Circular Sentence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def isCircularSentence(self, sentence: str) -> bool: 8 | words = sentence.split() 9 | n = len(words) 10 | return all(words[i][-1] == words[(i + 1) % n][0] for i in range(n)) 11 | 12 | 13 | class Solution: 14 | """ 15 | Time: O(n) 16 | Memory: O(1) 17 | """ 18 | 19 | def isCircularSentence(self, sentence: str) -> bool: 20 | for i, c in enumerate(sentence): 21 | if c == ' ' and sentence[i - 1] != sentence[i + 1]: 22 | return False 23 | return sentence[0] == sentence[-1] 24 | -------------------------------------------------------------------------------- /Python/Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def climbStairs(self, n: int) -> int: 11 | @lru_cache(None) 12 | def ways(i: int) -> int: 13 | if i > n: 14 | return 0 15 | elif i == n: 16 | return 1 17 | return ways(i + 1) + ways(i + 2) 18 | 19 | return ways(0) 20 | -------------------------------------------------------------------------------- /Python/Clumsy Factorial.py: -------------------------------------------------------------------------------- 1 | from itertools import cycle 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | OPERATIONS = ('*', '//', '+', '-') 11 | 12 | def clumsy(self, n: int) -> int: 13 | op = cycle(self.OPERATIONS) 14 | return eval(''.join(f'{n}{next(op)}' for n in range(n, 1, -1)) + '1') 15 | 16 | 17 | class Solution: 18 | """ 19 | Time: O(1) 20 | Memory: O(1) 21 | """ 22 | 23 | def clumsy(self, n: int) -> int: 24 | if n <= 2: 25 | return n 26 | if n <= 4: 27 | return n + 3 28 | if (n - 4) % 4 == 0: 29 | return n + 1 30 | if (n - 4) % 4 <= 2: 31 | return n + 2 32 | return n - 1 33 | -------------------------------------------------------------------------------- /Python/Combination Sum IV.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(2^n) 8 | Memory: O(n) 9 | """ 10 | 11 | def combinationSum4(self, nums: List[int], target: int) -> int: 12 | @lru_cache(maxsize=None) 13 | def dp(target: int) -> int: 14 | if target == 0: 15 | return 1 16 | if target < 0: 17 | return 0 18 | return sum(dp(target - num) for num in nums) 19 | 20 | return dp(target) 21 | -------------------------------------------------------------------------------- /Python/Compare Version Numbers.py: -------------------------------------------------------------------------------- 1 | from itertools import zip_longest 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(max(n,m)) 7 | Memory: O(n+m) 8 | """ 9 | 10 | def compareVersion(self, version1: str, version2: str) -> int: 11 | for v1, v2 in zip_longest( 12 | map(int, version1.split('.')), 13 | map(int, version2.split('.')), 14 | fillvalue=0 15 | ): 16 | if v1 > v2: 17 | return 1 18 | if v1 < v2: 19 | return -1 20 | 21 | return 0 22 | -------------------------------------------------------------------------------- /Python/Concatenation of Consecutive Binary Numbers.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log(n)) 7 | Memory: O(n*log(n)) 8 | """ 9 | 10 | MOD = 10 ** 9 + 7 11 | 12 | def concatenatedBinary(self, n: int) -> int: 13 | return int(''.join(bin(n)[2:] for n in range(1, n + 1)), 2) % self.MOD 14 | 15 | 16 | class Solution: 17 | """ 18 | Time: O(n*log(n)) 19 | Memory: O(1) 20 | """ 21 | 22 | MOD = 10 ** 9 + 7 23 | 24 | def concatenatedBinary(self, n: int) -> int: 25 | return reduce(lambda x, y: ((x << y.bit_length()) | y) % self.MOD, range(1, n + 1)) 26 | -------------------------------------------------------------------------------- /Python/Container With Most Water.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def maxArea(self, height: List[int]) -> int: 11 | left, right = 0, len(height) - 1 12 | max_area = 0 13 | 14 | while left < right: 15 | area = min(height[left], height[right]) * (right - left) 16 | max_area = max(area, max_area) 17 | 18 | if height[left] <= height[right]: 19 | left += 1 20 | else: 21 | right -= 1 22 | 23 | return max_area 24 | -------------------------------------------------------------------------------- /Python/Contains Duplicate II.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 11 | index = {} 12 | 13 | for i, num in enumerate(nums): 14 | if num in index and i - index[num] <= k: 15 | return True 16 | index[num] = i 17 | 18 | return False 19 | -------------------------------------------------------------------------------- /Python/Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def containsDuplicate(self, nums: List[int]) -> bool: 11 | seen = set() 12 | 13 | for num in nums: 14 | if num in seen: 15 | return True 16 | seen.add(num) 17 | 18 | return False 19 | -------------------------------------------------------------------------------- /Python/Continuous Subarray Sum.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def checkSubarraySum(self, nums: List[int], k: int) -> bool: 11 | hash_map = {0: 0} 12 | s = 0 13 | 14 | for i, num in enumerate(nums): 15 | s += num 16 | if s % k not in hash_map: 17 | hash_map[s % k] = i + 1 18 | elif hash_map[s % k] < i: 19 | return True 20 | 21 | return False 22 | -------------------------------------------------------------------------------- /Python/Convert 1D Array Into 2D Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(1) 8 | """ 9 | 10 | def construct2DArray(self, original: List[int], n: int, m: int) -> List[List[int]]: 11 | if len(original) != n * m: 12 | return [] 13 | return [[original[i * m + j] for j in range(m)] for i in range(n)] 14 | -------------------------------------------------------------------------------- /Python/Count Asterisks.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def countAsterisks(self, s: str) -> int: 8 | is_closed = True 9 | count = 0 10 | 11 | for c in s: 12 | count += is_closed * c == '*' 13 | is_closed ^= c == '|' 14 | 15 | return count 16 | 17 | 18 | class Solution: 19 | """ 20 | Time: O(n) 21 | Memory: O(n) 22 | """ 23 | 24 | def countAsterisks(self, s: str) -> int: 25 | return sum(chunk.count('*') for chunk in s.split('|')[0::2]) 26 | -------------------------------------------------------------------------------- /Python/Count Binary Substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def countBinarySubstrings(self, s: str) -> int: 8 | substrings = 0 9 | prev, curr = 0, 1 10 | 11 | for i in range(1, len(s)): 12 | if s[i - 1] != s[i]: 13 | substrings += min(prev, curr) 14 | prev, curr = curr, 1 15 | else: 16 | curr += 1 17 | 18 | return substrings + min(prev, curr) 19 | -------------------------------------------------------------------------------- /Python/Count Days Spent Together.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(1) 7 | Memory: O(1) 8 | """ 9 | 10 | def countDaysTogether(self, arrive_alice: str, leave_alice: str, arrive_bob: str, leave_bob: str) -> int: 11 | start = max(self.to_date(arrive_alice), self.to_date(arrive_bob)) 12 | end = min(self.to_date(leave_alice), self.to_date(leave_bob)) 13 | return max((end - start).days + 1, 0) 14 | 15 | @staticmethod 16 | def to_date(month_day: str) -> date: 17 | return date(2001, *map(int, month_day.split('-'))) 18 | -------------------------------------------------------------------------------- /Python/Count Distinct Numbers on Board.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | def distinctIntegers(self, n: int) -> int: 8 | return max(1, n - 1) 9 | -------------------------------------------------------------------------------- /Python/Count Number of Bad Pairs.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def countBadPairs(self, nums: List[int]) -> int: 12 | return sum(x * (len(nums) - x) for x in Counter(i - num for i, num in enumerate(nums)).values()) // 2 13 | -------------------------------------------------------------------------------- /Python/Count Number of Distinct Integers After Reverse Operations.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def countDistinctIntegers(self, nums: List[int]) -> int: 11 | uniq = set() 12 | 13 | for num in nums: 14 | uniq.add(num) 15 | uniq.add(int(str(num)[::-1])) 16 | 17 | return len(uniq) 18 | -------------------------------------------------------------------------------- /Python/Count Odd Numbers in an Interval Range.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | def countOdds(self, low: int, high: int) -> int: 8 | return (high + 1) // 2 - low // 2 9 | -------------------------------------------------------------------------------- /Python/Count Prefixes of a Given String.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(n*m) 8 | """ 9 | 10 | def countPrefixes(self, words: List[str], s: str) -> int: 11 | return sum(map(s.startswith, words)) 12 | -------------------------------------------------------------------------------- /Python/Count Unreachable Pairs of Nodes in an Undirected Graph.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(V + E) 8 | Memory: O(V + E) 9 | """ 10 | 11 | def countPairs(self, n: int, edges: List[List[int]]) -> int: 12 | def dfs(u: int, visited: set = set()) -> int: 13 | if u in visited: 14 | return 0 15 | visited.add(u) 16 | return 1 + sum(dfs(v) for v in graph[u]) 17 | 18 | graph = defaultdict(set) 19 | for u, v in edges: 20 | graph[u].add(v) 21 | graph[v].add(u) 22 | 23 | return sum(reached * (n - reached) for reached in map(dfs, range(n))) // 2 24 | -------------------------------------------------------------------------------- /Python/Count Vowels Permutation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | MOD = 10 ** 9 + 7 8 | 9 | def countVowelPermutation(self, n: int) -> int: 10 | a, e, i, o, u = 1, 1, 1, 1, 1 11 | 12 | for _ in range(n - 1): 13 | a, e, i, o, u = e + i + u, a + i, e + o, i, i + o 14 | 15 | return (a + e + i + o + u) % self.MOD 16 | -------------------------------------------------------------------------------- /Python/Count the Number of Consistent Strings.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n+m) 7 | Memory: O(n+m) 8 | 9 | where m - maximum word length 10 | """ 11 | 12 | def countConsistentStrings(self, allowed: str, words: List[str]) -> int: 13 | allowed = set(allowed) 14 | return sum(not set(other) - allowed for other in words) 15 | -------------------------------------------------------------------------------- /Python/Count the Number of Fair Pairs.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect, bisect_left 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(sort) 8 | Memory: O(1) 9 | """ 10 | 11 | def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: 12 | nums.sort() 13 | return sum( 14 | bisect(nums, upper - num, hi=i) - bisect_left(nums, lower - num, hi=i) 15 | for i, num in enumerate(nums) 16 | ) 17 | -------------------------------------------------------------------------------- /Python/Counting Words With a Given Prefix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*k) 7 | Memory: O(1) 8 | 9 | where k - prefix length 10 | """ 11 | 12 | def prefixCount(self, words: List[str], prefix: str) -> int: 13 | return sum(w.startswith(prefix) for w in words) 14 | -------------------------------------------------------------------------------- /Python/Custom Sort String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n*log(n)) 4 | Memory: O(n+m) 5 | 6 | where n - length of s 7 | m - length of order 8 | """ 9 | 10 | def customSortString(self, order: str, s: str) -> str: 11 | weight = {c: w for w, c in enumerate(order)} 12 | return ''.join(sorted(s, key=lambda x: weight.get(x, -1))) 13 | -------------------------------------------------------------------------------- /Python/Decode Ways.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def numDecodings(self, s: str) -> int: 11 | @lru_cache(maxsize=None) 12 | def dp(i: int): 13 | if i < n and s[i] == '0': 14 | return 0 15 | if n - i < 2: 16 | return 1 17 | return dp(i + 1) + (int(s[i:i + 2]) <= 26) * dp(i + 2) 18 | 19 | n = len(s) 20 | return dp(0) 21 | -------------------------------------------------------------------------------- /Python/Delete Columns to Make Sorted.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(m*n*log2(n)) 7 | Memory: O(n) 8 | """ 9 | 10 | def minDeletionSize(self, grid: List[str]) -> int: 11 | return sum(list(col) != sorted(col) for col in zip(*grid)) 12 | -------------------------------------------------------------------------------- /Python/Delete Node in a Linked List.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.next = None 5 | 6 | 7 | class Solution: 8 | """ 9 | Time: O(1) 10 | Memory: O(1) 11 | """ 12 | 13 | def deleteNode(self, node: ListNode): 14 | node.val = node.next.val 15 | node.next = node.next.next 16 | -------------------------------------------------------------------------------- /Python/Delete the Middle Node of a Linked List.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | 10 | class Solution: 11 | """ 12 | Time: O(n) 13 | Memory: O(1) 14 | """ 15 | 16 | def deleteMiddle(self, head: ListNode) -> Optional[ListNode]: 17 | if head.next is None: 18 | return None 19 | 20 | slow, fast = head, head.next.next 21 | while fast and fast.next: 22 | slow = slow.next 23 | fast = fast.next.next 24 | 25 | slow.next = slow.next.next 26 | return head 27 | -------------------------------------------------------------------------------- /Python/Design a Stack With Increment Operation.py: -------------------------------------------------------------------------------- 1 | class CustomStack: 2 | def __init__(self, maxsize: int): 3 | self.stack = [] 4 | self.maxsize = maxsize 5 | 6 | def push(self, x: int) -> None: 7 | if len(self.stack) < self.maxsize: 8 | self.stack.append(x) 9 | 10 | def pop(self) -> int: 11 | if self.stack: 12 | return self.stack.pop() 13 | return - 1 14 | 15 | def increment(self, k: int, val: int) -> None: 16 | for i in range(min(k, len(self.stack))): 17 | self.stack[i] += val 18 | -------------------------------------------------------------------------------- /Python/Detect Capital.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def detectCapitalUse(self, word: str) -> bool: 8 | return word.isupper() or word.islower() or word.istitle() 9 | -------------------------------------------------------------------------------- /Python/Determine if Two Events Have Conflict.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(1) 7 | Memory: O(1) 8 | """ 9 | 10 | def haveConflict(self, a: List[str], b: List[str]) -> bool: 11 | a_start, a_end = a 12 | b_start, b_end = b 13 | return b_start <= a_start <= b_end or \ 14 | b_start <= a_end <= b_end or \ 15 | a_start <= b_start <= a_end or \ 16 | a_start <= b_end <= a_end 17 | -------------------------------------------------------------------------------- /Python/Determine if Two Strings Are Close.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def closeStrings(self, a: str, b: str) -> bool: 11 | a_cnt, b_cnt = Counter(a), Counter(b) 12 | return a_cnt.keys() == b_cnt.keys() and sorted(a_cnt.values()) == sorted(b_cnt.values()) 13 | -------------------------------------------------------------------------------- /Python/Difference Between Ones and Zeros in Row and Column.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(n+m) 8 | """ 9 | 10 | def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]: 11 | n, m = len(grid), len(grid[0]) 12 | 13 | rows = [0] * n 14 | cols = [0] * m 15 | 16 | for i in range(n): 17 | for j in range(m): 18 | rows[i] += 1 if grid[i][j] else -1 19 | cols[j] += 1 if grid[i][j] else -1 20 | 21 | for i in range(n): 22 | for j in range(m): 23 | grid[i][j] = rows[i] + cols[j] 24 | 25 | return grid 26 | -------------------------------------------------------------------------------- /Python/Distance Between Bus Stops.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: 11 | i, j = sorted((start, destination)) 12 | clockwise = sum(distance[i:j]) 13 | counterclockwise = sum(distance[:i] + distance[j:]) 14 | return min(clockwise, counterclockwise) 15 | -------------------------------------------------------------------------------- /Python/Distribute Candies.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def distributeCandies(self, candy_types: List[int]) -> int: 11 | unique_candies = len(set(candy_types)) 12 | return min(unique_candies, len(candy_types) // 2) 13 | -------------------------------------------------------------------------------- /Python/Divide Intervals Into Minimum Number of Groups.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def minGroups(self, intervals: List[List[int]]) -> int: 11 | schedule = [] 12 | for start, end in intervals: 13 | schedule.append([start, 1]) 14 | schedule.append([end + 1, -1]) 15 | 16 | min_groups = groups = 0 17 | for _, diff in sorted(schedule): 18 | groups += diff 19 | min_groups = max(min_groups, groups) 20 | 21 | return min_groups 22 | -------------------------------------------------------------------------------- /Python/Divide Players Into Teams of Equal Skill.py: -------------------------------------------------------------------------------- 1 | from math import prod 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def dividePlayers(self, skill: List[int]) -> int: 7 | n = len(skill) 8 | skill.sort() 9 | 10 | teams = [(skill[i], skill[n - 1 - i]) for i in range(n // 2)] 11 | 12 | if len(set(map(sum, teams))) != 1: 13 | return -1 14 | 15 | return sum(map(prod, teams)) 16 | -------------------------------------------------------------------------------- /Python/Earliest Possible Day of Full Bloom.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log(n)) 7 | Memory: O(n) 8 | """ 9 | 10 | def earliestFullBloom(self, plant_time: List[int], grow_time: List[int]) -> int: 11 | result = curr_plant_time = 0 12 | 13 | for i in sorted(range(len(plant_time)), key=lambda x: -grow_time[x]): 14 | curr_plant_time += plant_time[i] 15 | result = max(result, curr_plant_time + grow_time[i]) 16 | 17 | return result 18 | -------------------------------------------------------------------------------- /Python/Evaluate Boolean Binary Tree.py: -------------------------------------------------------------------------------- 1 | from operator import and_, or_ 2 | from typing import Optional 3 | 4 | 5 | class TreeNode: 6 | def __init__(self, val=0, left=None, right=None): 7 | self.val = val 8 | self.left = left 9 | self.right = right 10 | 11 | 12 | class Solution: 13 | """ 14 | Time: O(n) 15 | Memory: O(n) 16 | """ 17 | 18 | MAPPING = { 19 | 0: lambda *_: False, 20 | 1: lambda *_: True, 21 | 2: or_, 22 | 3: and_, 23 | } 24 | 25 | def evaluateTree(self, root: Optional[TreeNode]) -> bool: 26 | if root is not None: 27 | return self.MAPPING[root.val]( 28 | self.evaluateTree(root.left), 29 | self.evaluateTree(root.right), 30 | ) 31 | -------------------------------------------------------------------------------- /Python/Evaluate Reverse Polish Notation.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | OPERATORS = { 11 | '+': lambda y, x: x + y, 12 | '-': lambda y, x: x - y, 13 | '*': lambda y, x: x * y, 14 | '/': lambda y, x: int(x / y) 15 | } 16 | 17 | def evalRPN(self, tokens: List[int]) -> int: 18 | stack = [] 19 | 20 | for token in tokens: 21 | if token in self.OPERATORS: 22 | a, b = stack.pop(), stack.pop() 23 | stack.append(self.OPERATORS[token](a, b)) 24 | else: 25 | stack.append(int(token)) 26 | 27 | return stack.pop() 28 | -------------------------------------------------------------------------------- /Python/Excel Sheet Column Title.py: -------------------------------------------------------------------------------- 1 | from string import ascii_uppercase 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(log26(n)) 7 | Memory: O(1) 8 | """ 9 | 10 | def convertToTitle(self, column_num: int) -> str: 11 | title = '' 12 | 13 | while column_num: 14 | column_num, ltr = divmod(column_num - 1, 26) 15 | title = ascii_uppercase[ltr] + title 16 | 17 | return title 18 | -------------------------------------------------------------------------------- /Python/Factorial Trailing Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log5(n)) 4 | Memory: O(log5(n)) 5 | """ 6 | 7 | def trailingZeroes(self, n: int) -> int: 8 | if n == 0: 9 | return 0 10 | return n // 5 + self.trailingZeroes(n // 5) 11 | -------------------------------------------------------------------------------- /Python/Find Duplicate File in System.py: -------------------------------------------------------------------------------- 1 | import re 2 | from collections import defaultdict 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | """ 8 | Time: O(n*k) 9 | Memory: O(n*k) 10 | 11 | where k - maximum number of files in one path 12 | """ 13 | 14 | def findDuplicate(self, paths: List[str]) -> List[List[str]]: 15 | duplicates = defaultdict(list) 16 | 17 | for path in paths: 18 | path, files = path.split(' ', 1) 19 | for file in files.split(): 20 | filename, content, _ = re.split(r'[\(\)]', file) 21 | duplicates[content].append(path + '/' + filename) 22 | 23 | return [p for p in duplicates.values() if len(p) > 1] 24 | -------------------------------------------------------------------------------- /Python/Find Original Array From Doubled Array.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n+k*log(k)) 8 | Memory: O(k) 9 | 10 | where k - number of unique numbers 11 | """ 12 | 13 | def findOriginalArray(self, changed: List[int]) -> List[int]: 14 | c = Counter(changed) 15 | 16 | if c[0] % 2: 17 | return [] 18 | 19 | for x in sorted(c): 20 | if c[x] > c[2 * x]: 21 | return [] 22 | c[2 * x] -= c[x] if x else c[x] // 2 23 | 24 | return list(c.elements()) 25 | -------------------------------------------------------------------------------- /Python/Find Players With Zero or One Losses.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(n)) 8 | Memory: O(n) 9 | """ 10 | 11 | def findWinners(self, matches: List[List[int]]) -> List[List[int]]: 12 | loses = defaultdict(int) 13 | wins = defaultdict(int) 14 | 15 | for w, l in matches: 16 | loses[l] += 1 17 | wins[w] += 1 18 | 19 | return [ 20 | sorted(w for w in wins if not loses[w]), 21 | sorted(l for l in loses if loses[l] == 1), 22 | ] 23 | -------------------------------------------------------------------------------- /Python/Find Positive Integer Solution for a Given Equation.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(N + M) 7 | Memory: O(1) 8 | 9 | where N - max 'x' value, 10 | M - max 'y' value 11 | """ 12 | 13 | def findSolution(self, custom_function: 'CustomFunction', z: int) -> List[List[int]]: 14 | x, y = 1, z 15 | pairs = [] 16 | 17 | while x <= z and y > 0: 18 | val = custom_function.f(x, y) 19 | if val == z: 20 | pairs.append([x, y]) 21 | if val >= z: 22 | y -= 1 23 | if val <= z: 24 | x += 1 25 | 26 | return pairs 27 | -------------------------------------------------------------------------------- /Python/Find Resultant Array After Removing Anagrams.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*k) 8 | Memory: O(k) 9 | 10 | where k - the longest word length 11 | """ 12 | 13 | def removeAnagrams(self, words: List[str]) -> List[str]: 14 | prev = Counter() 15 | result = [] 16 | 17 | for word in words: 18 | curr = Counter(word) 19 | if prev != curr: 20 | prev = Counter(word) 21 | result.append(word) 22 | 23 | return result 24 | -------------------------------------------------------------------------------- /Python/Find Subarrays With Equal Sum.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def findSubarrays(self, nums: List[int]) -> bool: 11 | sums = set() 12 | 13 | for i in range(len(nums) - 1): 14 | subarray = nums[i] + nums[i + 1] 15 | if subarray in sums: 16 | return True 17 | sums.add(subarray) 18 | 19 | return False 20 | -------------------------------------------------------------------------------- /Python/Find The Original Array of Prefix Xor.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def findArray(self, pref: List[int]) -> List[int]: 11 | for i in reversed(range(1, len(pref))): 12 | pref[i] ^= pref[i - 1] 13 | return pref 14 | -------------------------------------------------------------------------------- /Python/Find and Replace Pattern.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*k) 7 | Memory: O(k) 8 | 9 | k - length of each word 10 | n - length of pattern 11 | """ 12 | 13 | def findAndReplacePattern(self, words: List[str], pattern: str): 14 | def match(word: str) -> bool: 15 | mapping = {} 16 | 17 | for x, y in zip(pattern, word): 18 | if mapping.setdefault(x, y) != y: 19 | return False 20 | 21 | return len(set(mapping.values())) == len(mapping.values()) 22 | 23 | return filter(match, words) 24 | -------------------------------------------------------------------------------- /Python/Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log(k)) 4 | Memory: O(log(k)) 5 | """ 6 | 7 | def findMinFibonacciNumbers(self, k: int) -> int: 8 | if k < 2: 9 | return k 10 | return self.findMinFibonacciNumbers(k - self.min_fib(k)) + 1 11 | 12 | @staticmethod 13 | def min_fib(n: int) -> int: 14 | a, b = 1, 1 15 | while b <= n: 16 | a, b = b, a + b 17 | return a 18 | -------------------------------------------------------------------------------- /Python/Find the Pivot Integer.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(√n) 7 | Memory: O(1) 8 | """ 9 | 10 | def pivotInteger(self, n: int) -> int: 11 | m = sqrt(n * (n + 1) / 2) 12 | return int(m) if m.is_integer() else -1 13 | -------------------------------------------------------------------------------- /Python/Find the Town Judge.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def findJudge(self, n: int, trust: List[List[int]]) -> int: 11 | trust_to, trusted = [0] * n, [0] * n 12 | 13 | for u, v in trust: 14 | trust_to[u - 1] += 1 15 | trusted[v - 1] += 1 16 | 17 | for town, (tr, tr_to) in enumerate(zip(trusted, trust_to), start=1): 18 | if tr_to == 0 and tr == n - 1: 19 | return town 20 | 21 | return -1 22 | -------------------------------------------------------------------------------- /Python/Finding the Users Active Minutes.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n + k) 9 | """ 10 | 11 | def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]: 12 | active_minutes = defaultdict(set) 13 | 14 | for user_id, minute in logs: 15 | active_minutes[user_id].add(minute) 16 | 17 | uam = [0] * k 18 | for minutes in active_minutes.values(): 19 | uam[len(minutes) - 1] += 1 20 | 21 | return uam 22 | -------------------------------------------------------------------------------- /Python/First Bad Version.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log(n)) 4 | Memory: O(1) 5 | """ 6 | 7 | def firstBadVersion(self, n: int) -> int: 8 | left, right = 1, n 9 | 10 | while left <= right: 11 | mid = (left + right) >> 1 12 | if isBadVersion(mid): 13 | right = mid - 1 14 | else: 15 | left = mid + 1 16 | 17 | return left 18 | -------------------------------------------------------------------------------- /Python/First Letter to Appear Twice.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def repeatedCharacter(self, s: str) -> str: 8 | seen = set() 9 | 10 | for c in s: 11 | if c in seen: 12 | return c 13 | seen.add(c) 14 | -------------------------------------------------------------------------------- /Python/First Unique Character in a String.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def firstUniqChar(self, string: str) -> int: 11 | count = Counter(string) 12 | 13 | for i, ch in enumerate(string): 14 | if count[ch] == 1: 15 | return i 16 | 17 | return -1 18 | -------------------------------------------------------------------------------- /Python/Flip String to Monotone Increasing.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def minFlipsMonoIncr(self, s: str) -> int: 8 | ones = flip = 0 9 | 10 | for ch in s: 11 | if ch == '1': 12 | ones += 1 13 | else: 14 | flip += 1 15 | flip = min(ones, flip) 16 | 17 | return flip 18 | -------------------------------------------------------------------------------- /Python/Fruit Into Baskets.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(k) 9 | """ 10 | 11 | K = 2 12 | 13 | def totalFruit(self, fruits: List[int]) -> int: 14 | window = defaultdict(int) 15 | max_fruits = i = 0 16 | 17 | for j, tree in enumerate(fruits): 18 | window[tree] += 1 19 | 20 | while len(window) > self.K: 21 | window[fruits[i]] -= 1 22 | if not window[fruits[i]]: 23 | window.pop(fruits[i]) 24 | i += 1 25 | 26 | max_fruits = max(max_fruits, j - i + 1) 27 | 28 | return max_fruits 29 | -------------------------------------------------------------------------------- /Python/Generate Parentheses.py: -------------------------------------------------------------------------------- 1 | from typing import Generator 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(2^n) 7 | Memory: O(n) 8 | """ 9 | 10 | def generateParenthesis(self, n: int) -> Generator: 11 | return self._generate(opened=n, closed=n, string='') 12 | 13 | @classmethod 14 | def _generate(cls, opened: int, closed: int, string: str) -> Generator: 15 | if opened == closed == 0: 16 | yield string 17 | if closed >= opened: 18 | if opened: 19 | yield from cls._generate(opened - 1, closed, string + '(') 20 | if closed: 21 | yield from cls._generate(opened, closed - 1, string + ')') 22 | -------------------------------------------------------------------------------- /Python/Get Maximum in Generated Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def getMaximumGenerated(self, n: int) -> int: 8 | nums = [0, 1] + [0] * n 9 | 10 | for i in range(n + 1): 11 | nums[i] = nums[i // 2] + nums[i // 2 + 1] * (i & 1) 12 | 13 | return max(nums[:-1]) 14 | -------------------------------------------------------------------------------- /Python/Gray Code.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(2^n) 7 | Memory: O(1) 8 | """ 9 | 10 | def grayCode(self, n: int) -> List[int]: 11 | return [i ^ (i >> 1) for i in range(1 << n)] 12 | -------------------------------------------------------------------------------- /Python/Greatest Common Divisor of Strings.py: -------------------------------------------------------------------------------- 1 | from math import gcd 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n+m) 7 | Memory: O(n+m) 8 | """ 9 | 10 | def gcdOfStrings(self, a: str, b: str) -> str: 11 | n, m = len(a), len(b) 12 | return '' if a + b != b + a else a[:gcd(n, m)] 13 | -------------------------------------------------------------------------------- /Python/Group Anagrams.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*m*log(m)) 8 | Memory: O(n*m) 9 | 10 | where m - max string length 11 | """ 12 | 13 | def groupAnagrams(self, string: List[str]): 14 | anagrams = defaultdict(list) 15 | 16 | for s in string: 17 | anagrams[''.join(sorted(s))].append(s) 18 | 19 | return anagrams.values() 20 | -------------------------------------------------------------------------------- /Python/Groups of Special-Equivalent Strings.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*k*log(k)) 7 | Memory: O(n*k) 8 | 9 | where k - maximum word length 10 | """ 11 | 12 | def numSpecialEquivGroups(self, words: List[str]) -> int: 13 | return len({ 14 | ( 15 | ''.join(sorted(word[::2])), 16 | ''.join(sorted(word[1::2])), 17 | ) 18 | for word in words 19 | }) 20 | -------------------------------------------------------------------------------- /Python/Guess Number Higher or Lower.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log(n)) 4 | Memory: O(1) 5 | """ 6 | 7 | def guessNumber(self, n: int) -> int: 8 | left, right = 1, n 9 | 10 | while left <= right: 11 | mid = (left + right) // 2 12 | pick = guess(mid) 13 | 14 | if pick == 0: 15 | return mid 16 | 17 | if pick < 0: 18 | right = mid - 1 19 | else: 20 | left = mid + 1 21 | 22 | return -1 23 | -------------------------------------------------------------------------------- /Python/House Robber.py: -------------------------------------------------------------------------------- 1 | from functools import cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def rob(self, nums: List[int]) -> int: 12 | @cache 13 | def dp(i: int) -> int: 14 | if i < 0: 15 | return 0 16 | return max(dp(i - 1), dp(i - 2) + nums[i]) 17 | 18 | return dp(len(nums) - 1) 19 | -------------------------------------------------------------------------------- /Python/Image Overlap.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n^4) 8 | Memory: O(1) 9 | """ 10 | 11 | def largestOverlap(self, a: List[List[int]], b: List[List[int]]) -> int: 12 | a_ones_coords = [(x, y) for x, row in enumerate(a) for y, item in enumerate(row) if item] 13 | b_ones_coords = [(x, y) for x, row in enumerate(b) for y, item in enumerate(row) if item] 14 | shifts = Counter((ax - bx, ay - by) for ax, ay in a_ones_coords for bx, by in b_ones_coords) 15 | return max(shifts.values(), default=0) 16 | -------------------------------------------------------------------------------- /Python/Increasing Triplet Subsequence.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(1) 9 | """ 10 | 11 | def increasingTriplet(self, nums: List[int]) -> bool: 12 | first_min = second_min = maxsize 13 | 14 | for num in nums: 15 | if num <= first_min: 16 | first_min = num 17 | elif num <= second_min: 18 | second_min = num 19 | else: 20 | return True 21 | 22 | return False 23 | -------------------------------------------------------------------------------- /Python/Integer to Roman.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | ROMAN_TO_INTEGER = { 8 | 'M': 1000, 9 | 'CM': 900, 10 | 'D': 500, 11 | 'CD': 400, 12 | 'C': 100, 13 | 'XC': 90, 14 | 'L': 50, 15 | 'XL': 40, 16 | 'X': 10, 17 | 'IX': 9, 18 | 'V': 5, 19 | 'IV': 4, 20 | 'I': 1, 21 | } 22 | 23 | def intToRoman(self, num: int) -> str: 24 | converted = '' 25 | 26 | for roman, integer in self.ROMAN_TO_INTEGER.items(): 27 | whole, num = divmod(num, integer) 28 | converted += whole * roman 29 | 30 | return converted 31 | -------------------------------------------------------------------------------- /Python/Interval List Intersections.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n + m) 7 | Memory: O(n + m) 8 | """ 9 | 10 | def intervalIntersection(self, first: List[List[int]], second: List[List[int]]) -> List[List[int]]: 11 | i = j = 0 12 | intersection = [] 13 | 14 | while i < len(first) and j < len(second): 15 | a_start, a_end = first[i] 16 | b_start, b_end = second[j] 17 | 18 | start, end = max(a_start, b_start), min(a_end, b_end) 19 | if start <= end: 20 | intersection.append([start, end]) 21 | 22 | if a_end < b_end: 23 | i += 1 24 | else: 25 | j += 1 26 | 27 | return intersection 28 | -------------------------------------------------------------------------------- /Python/Invert Binary Tree.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, val=0, left=None, right=None): 6 | self.val = val 7 | self.left = left 8 | self.right = right 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(n) 14 | Memory: O(n) 15 | """ 16 | 17 | def invertTree(self, tree: Optional[TreeNode]) -> Optional[TreeNode]: 18 | if tree is not None: 19 | tree.left, tree.right = self.invertTree(tree.right), self.invertTree(tree.left) 20 | return tree 21 | -------------------------------------------------------------------------------- /Python/Jump Game III.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def canReach(self, arr: List[int], start: int): 11 | if not (0 <= start < len(arr)) or arr[start] < 0: 12 | return False 13 | if arr[start] == 0: 14 | return True 15 | 16 | arr[start] = -arr[start] 17 | left_search = self.canReach(arr, start + arr[start]) 18 | right_search = self.canReach(arr, start - arr[start]) 19 | arr[start] = -arr[start] 20 | 21 | return left_search or right_search 22 | -------------------------------------------------------------------------------- /Python/Jump Game.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def canJump(self, nums: List[int]) -> bool: 11 | max_ind = 0 12 | 13 | for i, num in enumerate(nums): 14 | if i > max_ind: 15 | return False 16 | max_ind = max(max_ind, i + num) 17 | 18 | return True 19 | -------------------------------------------------------------------------------- /Python/Keys and Rooms.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 12 | queue = deque([0]) 13 | unvisited = set(range(len(rooms))) 14 | 15 | while queue: 16 | v = queue.popleft() 17 | if v in unvisited: 18 | unvisited.remove(v) 19 | queue.extend(rooms[v]) 20 | 21 | return not unvisited 22 | -------------------------------------------------------------------------------- /Python/Koko Eating Bananas.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(M)) 8 | Memory: O(1) 9 | """ 10 | 11 | def minEatingSpeed(self, piles: List[int], h: int) -> int: 12 | def f(k: int) -> int: 13 | return sum(ceil(p / k) for p in piles) 14 | 15 | lo, hi = 1, 1_000_000_000 16 | 17 | while lo < hi: 18 | mid = (lo + hi) // 2 19 | 20 | if f(mid) > h: 21 | lo = mid + 1 22 | else: 23 | hi = mid 24 | 25 | return lo 26 | -------------------------------------------------------------------------------- /Python/Kth Missing Positive Number.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def findKthPositive(self, arr: List[int], k: int) -> int: 11 | seen = set(arr) 12 | for num in range(1, k + len(arr) + 1): 13 | if num not in seen: 14 | k -= 1 15 | if not k: 16 | return num 17 | -------------------------------------------------------------------------------- /Python/Largest 3-Same-Digit Number in String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | K = 3 8 | 9 | def largestGoodInteger(self, num: str) -> str: 10 | for d in reversed(range(10)): 11 | good = str(d) * self.K 12 | if good in num: 13 | return good 14 | return '' 15 | 16 | 17 | class Solution: 18 | """ 19 | Time: O(n) 20 | Memory: O(1) 21 | """ 22 | 23 | K = 3 24 | 25 | def largestGoodInteger(self, num: str) -> str: 26 | max_good = '' 27 | 28 | for i in range(2, len(num)): 29 | if num[i - 2] == num[i - 1] == num[i]: 30 | max_good = max(max_good, num[i]) 31 | 32 | return max_good * self.K 33 | -------------------------------------------------------------------------------- /Python/Largest Local Values in a Matrix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n^2) 7 | Memory: O(1) 8 | """ 9 | 10 | def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: 11 | n = len(grid) 12 | return [[self.local_max(grid, r, c, 1) for c in range(1, n - 1)] for r in range(1, n - 1)] 13 | 14 | @staticmethod 15 | def local_max(grid: List[List[int]], row: int, col: int, radius: int) -> int: 16 | return max( 17 | grid[r][c] 18 | for r in range(row - radius, row + radius + 1) 19 | for c in range(col - radius, col + radius + 1) 20 | ) 21 | -------------------------------------------------------------------------------- /Python/Largest Number At Least Twice of Others.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def dominantIndex(self, nums: List[int]) -> int: 11 | first_max = second_max = -1 12 | max_ind = 0 13 | 14 | for i, num in enumerate(nums): 15 | if num >= first_max: 16 | first_max, second_max = num, first_max 17 | max_ind = i 18 | elif num > second_max: 19 | second_max = num 20 | 21 | if first_max < 2 * second_max: 22 | max_ind = -1 23 | 24 | return max_ind 25 | -------------------------------------------------------------------------------- /Python/Largest Odd Number in String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def largestOddNumber(self, num: str) -> str: 8 | n = len(num) 9 | 10 | for i in reversed(range(n)): 11 | if int(num[i]) & 1: 12 | return num[:i + 1] 13 | 14 | return '' 15 | -------------------------------------------------------------------------------- /Python/Largest Palindromic Number.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(1) 7 | Memory: O(1) 8 | """ 9 | 10 | def largestPalindromic(self, num: str) -> str: 11 | count = Counter(num) 12 | palindrome = mid = '' 13 | 14 | for d in sorted(count.keys(), reverse=True): 15 | mid = max(mid, d * (count[d] & 1)) 16 | palindrome += d * (count[d] // 2) 17 | 18 | palindrome = palindrome.lstrip('0') 19 | return (palindrome + mid + palindrome[::-1]) or '0' 20 | -------------------------------------------------------------------------------- /Python/Largest Perimeter Triangle.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log(n)) 7 | Memory: O(1) 8 | """ 9 | 10 | def largestPerimeter(self, nums: List[int]) -> int: 11 | nums.sort(reverse=True) 12 | 13 | for i in range(len(nums) - 2): 14 | if nums[i + 2] + nums[i + 1] > nums[i]: 15 | return nums[i + 2] + nums[i + 1] + nums[i] 16 | 17 | return 0 18 | -------------------------------------------------------------------------------- /Python/Left and Right Sum Differences.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def leftRigthDifference(self, nums: List[int]) -> List[int]: 11 | n = len(nums) 12 | 13 | left_sum = [0] * n 14 | for i in range(n - 1, 0, -1): 15 | left_sum[i - 1] = left_sum[i] + nums[i] 16 | 17 | right_sum = [0] * n 18 | for i in range(n - 1): 19 | right_sum[i + 1] = right_sum[i] + nums[i] 20 | 21 | return [abs(l - r) for l, r in zip(left_sum, right_sum)] 22 | -------------------------------------------------------------------------------- /Python/Lemonade Change.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def lemonadeChange(self, bills: List[int]) -> bool: 11 | five = ten = 0 12 | 13 | for bill in bills: 14 | if bill == 5: 15 | five += 1 16 | elif bill == 10 and five > 0: 17 | ten += 1 18 | five -= 1 19 | elif bill == 20 and ten > 0 and five > 0: 20 | five -= 1 21 | ten -= 1 22 | elif bill == 20 and five >= 3: 23 | five -= 3 24 | else: 25 | return False 26 | 27 | return True 28 | -------------------------------------------------------------------------------- /Python/Length of the Longest Alphabetical Continuous Substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def longestContinuousSubstring(self, s: str) -> int: 8 | longest = current = 0 9 | prev = '*' 10 | 11 | for c in s: 12 | if ord(prev) + 1 != ord(c): 13 | current = 1 14 | else: 15 | current += 1 16 | 17 | prev = c 18 | longest = max(longest, current) 19 | 20 | return longest 21 | -------------------------------------------------------------------------------- /Python/Linked List Cycle.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class ListNode: 5 | def __init__(self, x): 6 | self.val = x 7 | self.next = None 8 | 9 | 10 | class Solution: 11 | """ 12 | Time: O(n) 13 | Memory: O(1) 14 | """ 15 | 16 | def hasCycle(self, head: Optional[ListNode]) -> bool: 17 | fast = head 18 | slow = head 19 | 20 | while fast and fast.next: 21 | slow = slow.next 22 | fast = fast.next.next 23 | if slow == fast: 24 | return True 25 | 26 | return False 27 | -------------------------------------------------------------------------------- /Python/Longer Contiguous Segments of Ones than Zeros.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def checkZeroOnes(self, string: str) -> bool: 8 | best_one = best_zero = current_one = current_zero = 0 9 | 10 | for c in string: 11 | if c == '1': 12 | current_zero = 0 13 | current_one += 1 14 | best_one = max(best_one, current_one) 15 | else: 16 | current_zero += 1 17 | current_one = 0 18 | best_zero = max(best_zero, current_zero) 19 | 20 | return best_one > best_zero 21 | -------------------------------------------------------------------------------- /Python/Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def longestCommonPrefix(self, strs: List[str]) -> str: 11 | min_str = min(strs) 12 | prefix = '' 13 | 14 | for ind, sym in enumerate(min_str): 15 | for other in strs: 16 | if other[ind] != sym: 17 | return prefix 18 | prefix += sym 19 | 20 | return prefix 21 | -------------------------------------------------------------------------------- /Python/Longest Increasing Subsequence.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(n)) 8 | Memory: O(n) 9 | """ 10 | 11 | def lengthOfLIS(self, nums: List[int]) -> int: 12 | seq = [] 13 | 14 | for x in nums: 15 | if not seq or seq[-1] < x: 16 | seq.append(x) 17 | else: 18 | seq[bisect_left(seq, x)] = x 19 | 20 | return len(seq) 21 | -------------------------------------------------------------------------------- /Python/Longest Nice Subarray.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def longestNiceSubarray(self, nums: List[int]) -> int: 11 | longest = used_bits = j = 0 12 | 13 | for i, num in enumerate(nums): 14 | while used_bits & num != 0: 15 | used_bits ^= nums[j] 16 | j += 1 17 | 18 | used_bits |= num 19 | longest = max(longest, i - j + 1) 20 | 21 | return longest 22 | -------------------------------------------------------------------------------- /Python/Longest Repeating Character Replacement.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def characterReplacement(self, s: str, k: int) -> int: 11 | freq = defaultdict(int) 12 | max_freq = max_len = i = 0 13 | 14 | for j in range(len(s)): 15 | freq[s[j]] += 1 16 | max_freq = max(max_freq, freq[s[j]]) 17 | 18 | if (j - i + 1) - max_freq > k: 19 | freq[s[i]] -= 1 20 | i += 1 21 | else: 22 | max_len = max(max_len, j - i + 1) 23 | 24 | return max_len 25 | -------------------------------------------------------------------------------- /Python/Longest Square Streak in an Array.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from math import sqrt 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | """ 8 | Time: O(n*√n) 9 | Memory: O(n) 10 | """ 11 | 12 | def longestSquareStreak(self, nums: List[int]) -> int: 13 | dp = defaultdict(int) 14 | 15 | longest = 1 16 | for i in sorted(nums): 17 | root = sqrt(i) 18 | 19 | if root.is_integer(): 20 | dp[i] = dp[int(root)] + 1 21 | longest = max(longest, dp[i]) 22 | else: 23 | dp[i] = 1 24 | 25 | return -1 if longest < 2 else longest 26 | -------------------------------------------------------------------------------- /Python/Longest String Chain.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*k^2) 7 | Memory: O(n) 8 | 9 | where k - max word length 10 | """ 11 | 12 | def longestStrChain(self, words: List[str]) -> int: 13 | words.sort(key=len) 14 | memo = {w: 1 for w in words} 15 | 16 | for word in words: 17 | for j in range(len(word)): 18 | memo[word] = max(memo[word], 1 + memo.get(word[:j] + word[j + 1:], 0)) 19 | 20 | return max(memo.values()) 21 | -------------------------------------------------------------------------------- /Python/Longest Subarray With Maximum Bitwise AND.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def longestSubarray(self, nums: List[int]) -> int: 11 | max_num = max(nums) 12 | longest = current = 0 13 | 14 | for num in nums: 15 | if num == max_num: 16 | current += 1 17 | else: 18 | current = 0 19 | longest = max(longest, current) 20 | 21 | return longest 22 | -------------------------------------------------------------------------------- /Python/Longest Subarray of 1's After Deleting One Element.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def longestSubarray(self, nums: List[int]) -> int: 11 | longest = prev = curr = 0 12 | 13 | for bit in nums: 14 | if bit: 15 | curr += 1 16 | longest = max(longest, prev + curr) 17 | else: 18 | prev, curr = curr, 0 19 | 20 | return longest - (longest == len(nums)) 21 | -------------------------------------------------------------------------------- /Python/Longest Subsequence With Limited Sum.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect 2 | from itertools import accumulate 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | """ 8 | Time: O(n*log(n)) 9 | Memory: O(n) 10 | """ 11 | 12 | def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: 13 | cumsum = list(accumulate(sorted(nums))) 14 | return [bisect(cumsum, q) for q in queries] 15 | -------------------------------------------------------------------------------- /Python/Longest Substring Of All Vowels in Order.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def longestBeautifulSubstring(self, word: str) -> int: 8 | longest = 0 9 | current = 1 10 | unique = 1 11 | 12 | for i in range(1, len(word)): 13 | if word[i - 1] > word[i]: 14 | current = 1 15 | unique = 1 16 | elif word[i - 1] < word[i]: 17 | current += 1 18 | unique += 1 19 | else: 20 | current += 1 21 | 22 | if unique == 5: 23 | longest = max(longest, current) 24 | 25 | return longest 26 | -------------------------------------------------------------------------------- /Python/Longest Substring Without Repeating Characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def lengthOfLongestSubstring(self, string: str) -> int: 8 | last_index = {} 9 | start_ind = max_length = 0 10 | 11 | for ind, ch in enumerate(string): 12 | if ch in last_index and start_ind <= last_index[ch]: 13 | start_ind = last_index[ch] + 1 14 | 15 | last_index[ch] = ind 16 | max_length = max(max_length, ind - start_ind + 1) 17 | 18 | return max_length 19 | -------------------------------------------------------------------------------- /Python/Longest Uploaded Prefix.py: -------------------------------------------------------------------------------- 1 | class LUPrefix: 2 | """ 3 | Memory: O(n) 4 | Time: O(1) per upload call, because adding to the set takes O(1) time, and the prefix 5 | can be increased no more than n times for all n calls to the upload function 6 | """ 7 | 8 | def __init__(self, n: int): 9 | self._longest = 0 10 | self._nums = set() 11 | 12 | def upload(self, video: int) -> None: 13 | self._nums.add(video) 14 | # Since the prefix cannot decrease, it is enough for us to increase it 15 | # until we reach the number that has not yet been added 16 | while self._longest + 1 in self._nums: 17 | self._longest += 1 18 | 19 | def longest(self) -> int: 20 | return self._longest 21 | -------------------------------------------------------------------------------- /Python/Make Array Zero by Subtracting Equal Amounts.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def minimumOperations(self, nums: List[int]) -> int: 11 | return len({num for num in nums if num != 0}) 12 | -------------------------------------------------------------------------------- /Python/Make The String Great.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def makeGood(self, s: str) -> str: 8 | stack = [] 9 | 10 | for c in s: 11 | if stack and c.swapcase() == stack[-1]: 12 | stack.pop() 13 | else: 14 | stack.append(c) 15 | 16 | return ''.join(stack) 17 | -------------------------------------------------------------------------------- /Python/Matrix Cells in Distance Order.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m*log(n*m)) 7 | Memory: O(1) 8 | """ 9 | 10 | def allCellsDistOrder(self, rows: int, cols: int, r_center: int, c_center: int) -> List[List[int]]: 11 | return sorted( 12 | [[r, c] for r in range(rows) for c in range(cols)], 13 | key=lambda x: abs(x[0] - r_center) + abs(x[1] - c_center), 14 | ) 15 | -------------------------------------------------------------------------------- /Python/Maximum 69 Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def maximum69Number(self, num: int) -> int: 8 | return int(str(num).replace('6', '9', 1)) 9 | -------------------------------------------------------------------------------- /Python/Maximum Average Subarray I.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def findMaxAverage(self, nums: List[int], k: int) -> float: 11 | max_sum = cur_sum = sum(nums[:k]) 12 | 13 | for i in range(k, len(nums)): 14 | cur_sum = cur_sum - nums[i - k] + nums[i] 15 | max_sum = max(max_sum, cur_sum) 16 | 17 | return max_sum / k 18 | -------------------------------------------------------------------------------- /Python/Maximum Bags With Full Capacity of Rocks.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log2(n)) 7 | Memory: O(n) 8 | """ 9 | 10 | def maximumBags(self, capacity: List[int], rocks: List[int], additional_rocks: int) -> int: 11 | count = sorted((c - r for c, r in zip(capacity, rocks)), reverse=True) 12 | 13 | while count and additional_rocks and count[-1] <= additional_rocks: 14 | additional_rocks -= count.pop() 15 | 16 | return len(rocks) - len(count) 17 | -------------------------------------------------------------------------------- /Python/Maximum Binary Tree II.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, val=0, left=None, right=None): 6 | self.val = val 7 | self.left = left 8 | self.right = right 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(n) 14 | Memory: O(n) 15 | """ 16 | 17 | def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: 18 | if root and root.val > val: 19 | root.right = self.insertIntoMaxTree(root.right, val) 20 | else: 21 | root = TreeNode(val, left=root) 22 | return root 23 | -------------------------------------------------------------------------------- /Python/Maximum Count of Positive Integer and Negative Integer.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left, bisect_right 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(log2(n)) 8 | Memory: O(1) 9 | """ 10 | 11 | def maximumCount(self, nums: List[int]) -> int: 12 | negative = bisect_left(nums, 0) 13 | positive = len(nums) - bisect_right(nums, 0) 14 | return max(negative, positive) 15 | -------------------------------------------------------------------------------- /Python/Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, val=0, left=None, right=None): 6 | self.val = val 7 | self.left = left 8 | self.right = right 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(n) 14 | Memory: O(n) 15 | """ 16 | 17 | def maxDepth(self, root: Optional[TreeNode]) -> int: 18 | return max( 19 | self.maxDepth(root.left), 20 | self.maxDepth(root.right), 21 | ) + 1 if root is not None else 0 22 | -------------------------------------------------------------------------------- /Python/Maximum Ice Cream Bars.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log2(n)) 7 | Memory: O(1) 8 | """ 9 | 10 | def maxIceCream(self, costs: List[int], coins: int) -> int: 11 | return sum((coins := coins - cost) >= 0 for cost in sorted(costs)) 12 | -------------------------------------------------------------------------------- /Python/Maximum Length of Repeated Subarray.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(n*m) 8 | """ 9 | 10 | def findLength(self, a: List[int], b: List[int]) -> int: 11 | n, m = len(a), len(b) 12 | dp = [[0] * (m + 1) for _ in range(n + 1)] 13 | 14 | for i in range(n): 15 | for j in range(m): 16 | if a[i] == b[j]: 17 | dp[i + 1][j + 1] = dp[i][j] + 1 18 | 19 | return max(map(max, dp)) 20 | -------------------------------------------------------------------------------- /Python/Maximum Length of a Concatenated String with Unique Characters.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n^2) 7 | Memory: O(n^2) 8 | """ 9 | 10 | def maxLength(self, sequences: List[str]) -> int: 11 | dp = [set()] 12 | 13 | for seq in sequences: 14 | chars = set(seq) 15 | 16 | if len(chars) < len(seq): 17 | continue 18 | 19 | dp.extend(chars | other for other in dp if not (chars & other)) 20 | 21 | return max(map(len, dp)) 22 | -------------------------------------------------------------------------------- /Python/Maximum Performance of a Team.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(n)) 8 | Memory: O(n) 9 | """ 10 | 11 | MOD = 10 ** 9 + 7 12 | 13 | def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: 14 | res = total_sum = 0 15 | heap = [] 16 | 17 | for e, s in sorted(zip(efficiency, speed), reverse=True): 18 | heappush(heap, s) 19 | total_sum += s 20 | if len(heap) > k: 21 | total_sum -= heappop(heap) 22 | res = max(res, total_sum * e) 23 | 24 | return res % self.MOD 25 | -------------------------------------------------------------------------------- /Python/Maximum Points You Can Obtain from Cards.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def maxScore(self, cards: List[int], k: int) -> int: 11 | n = len(cards) 12 | size = n - k 13 | min_window = window = sum(cards[:size]) 14 | 15 | for i in range(size, n): 16 | window += cards[i] - cards[i - size] 17 | min_window = min(min_window, window) 18 | 19 | return sum(cards) - min_window 20 | -------------------------------------------------------------------------------- /Python/Maximum Score from Performing Multiplication Operations.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(m^2) 7 | Memory: O(m) 8 | """ 9 | 10 | def maximumScore(self, nums: List[int], mult: List[int]) -> int: 11 | m = len(mult) 12 | dp = [0] * (m + 1) 13 | 14 | for i in reversed(range(m)): 15 | tmp = [0] * (i + 1) 16 | for l in reversed(range(i + 1)): 17 | tmp[l] = max( 18 | dp[l + 1] + mult[i] * nums[l], 19 | dp[l] + mult[i] * nums[~(i - l)], 20 | ) 21 | dp = tmp 22 | 23 | return dp[0] 24 | -------------------------------------------------------------------------------- /Python/Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(1) 9 | """ 10 | 11 | def maxSubArray(self, nums: List[int]) -> int: 12 | max_sum, curr_sum = -maxsize, 0 13 | 14 | for num in nums: 15 | curr_sum += num 16 | if max_sum < curr_sum: 17 | max_sum = curr_sum 18 | if curr_sum < 0: 19 | curr_sum = 0 20 | 21 | return max_sum 22 | -------------------------------------------------------------------------------- /Python/Maximum Sum of an Hourglass.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(n*m) 8 | """ 9 | 10 | def maxSum(self, grid: List[List[int]]) -> int: 11 | n, m = len(grid), len(grid[0]) 12 | return max( 13 | self.get_hourglass(grid, i, j) 14 | for i in range(1, n - 1) 15 | for j in range(1, m - 1) 16 | ) 17 | 18 | @staticmethod 19 | def get_hourglass(grid: List[List[int]], i: int, j: int) -> int: 20 | return grid[i - 1][j - 1] + grid[i - 1][j] + grid[i - 1][j + 1] + \ 21 | grid[i][j] + \ 22 | grid[i + 1][j - 1] + grid[i + 1][j] + grid[i + 1][j + 1] 23 | -------------------------------------------------------------------------------- /Python/Maximum of Absolute Value Expression.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def maxAbsValExpr(self, a: List[int], b: List[int]) -> int: 11 | points = [ 12 | ( 13 | x + y + i, 14 | x + y - i, 15 | x - y + i, 16 | x - y - i, 17 | ) 18 | for i, (x, y) in enumerate(zip(a, b)) 19 | ] 20 | return max(max(dim) - min(dim) for dim in zip(*points)) 21 | -------------------------------------------------------------------------------- /Python/Merge In Between Linked Lists.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | 7 | class Solution: 8 | """ 9 | Time: O(n+m) 10 | Memory: O(1) 11 | """ 12 | 13 | def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: 14 | start, end = None, list1 15 | 16 | for i in range(b): 17 | if i == a - 1: 18 | start = end 19 | end = end.next 20 | 21 | start.next = list2 22 | while list2.next: 23 | list2 = list2.next 24 | list2.next = end.next 25 | 26 | return list1 27 | -------------------------------------------------------------------------------- /Python/Merge Similar Items.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(n)) 8 | Memory: O(n) 9 | 10 | where n - len(first) + len(second) 11 | """ 12 | 13 | def mergeSimilarItems(self, first: List[List[int]], second: List[List[int]]) -> List[List[int]]: 14 | merged = defaultdict(int) 15 | 16 | for value, weight in first + second: 17 | merged[value] += weight 18 | 19 | return sorted(merged.items()) 20 | -------------------------------------------------------------------------------- /Python/Merge Sorted Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n+m) 7 | Memory: O(1) 8 | """ 9 | 10 | def merge(self, first: List[int], n: int, second: List[int], m: int) -> None: 11 | i, j = n - 1, m - 1 12 | 13 | for curr in reversed(range(n + m)): 14 | if j < 0: 15 | first[curr] = first[i] 16 | i -= 1 17 | elif i < 0: 18 | first[curr] = second[j] 19 | j -= 1 20 | elif first[i] > second[j]: 21 | first[curr] = first[i] 22 | i -= 1 23 | else: 24 | first[curr] = second[j] 25 | j -= 1 26 | -------------------------------------------------------------------------------- /Python/Middle of the Linked List.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | 10 | class Solution: 11 | """ 12 | Time: O(n) 13 | Memory: O(1) 14 | """ 15 | 16 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 17 | slow = fast = head 18 | 19 | while fast and fast.next: 20 | slow = slow.next 21 | fast = fast.next.next 22 | 23 | return slow 24 | -------------------------------------------------------------------------------- /Python/Min Stack.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | 3 | 4 | class MinStack: 5 | """ 6 | Memory: 7 | creation - O(1), increases with calls 'push' 8 | 'popSmallest' and 'addBack' - O(1) 9 | 10 | Time: 11 | creation, 'popSmallest' and 'addBack' - O(1) 12 | """ 13 | 14 | def __init__(self): 15 | self.stack = [(maxsize, maxsize)] 16 | 17 | def push(self, val: int) -> None: 18 | self.stack.append((val, min(val, self.getMin()))) 19 | 20 | def pop(self) -> None: 21 | self.stack.pop() 22 | 23 | def top(self) -> int: 24 | val, _ = self.stack[-1] 25 | return val 26 | 27 | def getMin(self) -> int: 28 | _, minimum = self.stack[-1] 29 | return minimum 30 | -------------------------------------------------------------------------------- /Python/Minimum Add to Make Parentheses Valid.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def minAddToMakeValid(self, s: str) -> int: 8 | score = add = 0 9 | 10 | for ch in s: 11 | score += -1 if ch == ')' else 1 12 | if score < 0: 13 | add += 1 14 | score = 0 15 | 16 | return score + add 17 | -------------------------------------------------------------------------------- /Python/Minimum Amount of Time to Collect Garbage.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | TYPES = 'PGM' 11 | 12 | def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: 13 | last = {c: i for i, grb in enumerate(garbage) for c in grb} 14 | 15 | for i in range(1, len(travel)): 16 | travel[i] += travel[i - 1] 17 | 18 | return sum(map(len, garbage)) + sum(travel[i - 1] if i > 0 else 0 for c, i in last.items()) 19 | -------------------------------------------------------------------------------- /Python/Minimum Amount of Time to Fill Cups.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(1) 7 | Memory: O(1) 8 | """ 9 | 10 | def fillCups(self, amount: List[int]) -> int: 11 | c, w, h = amount 12 | return max(max(c, w, h), (c + w + h + 1) // 2) 13 | -------------------------------------------------------------------------------- /Python/Minimum Bit Flips to Convert Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log(n)) 4 | Memory: O(1) 5 | """ 6 | 7 | def minBitFlips(self, start: int, goal: int) -> int: 8 | return (start ^ goal).bit_count() 9 | -------------------------------------------------------------------------------- /Python/Minimum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, val=0, left=None, right=None): 6 | self.val = val 7 | self.left = left 8 | self.right = right 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(n) 14 | Memory: O(n) 15 | """ 16 | 17 | def minDepth(self, root: Optional[TreeNode]) -> int: 18 | if root is None: 19 | return 0 20 | 21 | left_depth = self.minDepth(root.left) 22 | right_depth = self.minDepth(root.right) 23 | 24 | return 1 + ( 25 | min(left_depth, right_depth) or 26 | max(left_depth, right_depth) 27 | ) 28 | -------------------------------------------------------------------------------- /Python/Minimum Difference Between Highest and Lowest of K Scores.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(n)) 8 | Memory: O(1) 9 | """ 10 | 11 | def minimumDifference(self, nums: List[int], k: int) -> int: 12 | min_diff = maxsize 13 | nums.sort() 14 | 15 | for i in range(k - 1, len(nums)): 16 | min_diff = min(min_diff, nums[i] - nums[i - k + 1]) 17 | 18 | return min_diff 19 | -------------------------------------------------------------------------------- /Python/Minimum Distance to the Target Element.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def getMinDistance(self, nums: List[int], target: int, start: int) -> int: 11 | return min(abs(i - start) for i in range(len(nums)) if nums[i] == target) 12 | -------------------------------------------------------------------------------- /Python/Minimum Domino Rotations For Equal Row.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: 11 | x = tops[0] 12 | if all(x == a or x == b for a, b in zip(tops, bottoms)): 13 | return len(tops) - max(tops.count(x), bottoms.count(x)) 14 | 15 | x = bottoms[0] 16 | if all(x == a or x == b for a, b in zip(tops, bottoms)): 17 | return len(tops) - max(tops.count(x), bottoms.count(x)) 18 | 19 | return -1 20 | -------------------------------------------------------------------------------- /Python/Minimum Falling Path Sum.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(1) 8 | """ 9 | 10 | def minFallingPathSum(self, matrix: List[List[int]]) -> int: 11 | n, m = len(matrix), len(matrix[0]) 12 | 13 | for i in range(1, n): 14 | for j in range(m): 15 | matrix[i][j] += min( 16 | matrix[i - 1][max( 0, j - 1)], 17 | matrix[i - 1][j], 18 | matrix[i - 1][min(m - 1, j + 1)], 19 | ) 20 | 21 | return min(matrix[-1]) 22 | -------------------------------------------------------------------------------- /Python/Minimum Number of Arrows to Burst Balloons.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log2(n)) 8 | Memory: O(1) 9 | """ 10 | 11 | def findMinArrowShots(self, points: List[List[int]]) -> int: 12 | points.sort(key=lambda x: x[1]) 13 | 14 | arrows = 0 15 | end = -maxsize 16 | 17 | for s, e in points: 18 | if s > end: 19 | arrows += 1 20 | end = e 21 | 22 | return arrows 23 | -------------------------------------------------------------------------------- /Python/Minimum Number of Steps to Make Two Strings Anagram II.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n+m) 7 | Memory: O(n+m) 8 | """ 9 | 10 | def minSteps(self, s: str, t: str) -> int: 11 | s_cnt = Counter(s) 12 | t_cnt = Counter(t) 13 | return sum((s_cnt - t_cnt).values()) + sum((t_cnt - s_cnt).values()) 14 | -------------------------------------------------------------------------------- /Python/Minimum Number of Steps to Make Two Strings Anagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def minSteps(self, s: str, t: str) -> int: 8 | count = [0] * 26 9 | 10 | for char in s: 11 | count[ord(char) - ord('a')] += 1 12 | 13 | for char in t: 14 | count[ord(char) - ord('a')] -= 1 15 | 16 | return sum(val for val in count if val > 0) 17 | -------------------------------------------------------------------------------- /Python/Minimum Number of Vertices to Reach All Nodes.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: 11 | seen = [False] * n 12 | 13 | for _, to in edges: 14 | seen[to] = True 15 | 16 | return [v for v, is_seen in enumerate(seen) if not is_seen] 17 | -------------------------------------------------------------------------------- /Python/Minimum Recolors to Get K Consecutive Black Blocks.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(k) 5 | """ 6 | 7 | def minimumRecolors(self, blocks: str, k: int) -> int: 8 | min_cost = cost = blocks[:k].count('W') 9 | 10 | for i in range(k, len(blocks)): 11 | cost = cost - (blocks[i - k] == 'W') + (blocks[i] == 'W') 12 | min_cost = min(min_cost, cost) 13 | 14 | return min_cost 15 | -------------------------------------------------------------------------------- /Python/Minimum Remove to Make Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def minRemoveToMakeValid(self, s): 8 | stack = [] 9 | chars = list(s) 10 | 11 | for i, ch in enumerate(chars): 12 | if s[i] == '(': 13 | stack.append(i) 14 | elif s[i] == ')': 15 | if stack: 16 | stack.pop() 17 | else: 18 | chars[i] = '' 19 | 20 | for i in stack: 21 | chars[i] = '' 22 | 23 | return ''.join(chars) 24 | -------------------------------------------------------------------------------- /Python/Minimum Rounds to Complete All Tasks.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def minimumRounds(self, tasks: List[int]) -> int: 12 | min_rounds = 0 13 | 14 | for cnt in Counter(tasks).values(): 15 | if cnt == 1: 16 | return -1 17 | min_rounds += cnt // 3 + int(cnt % 3 != 0) 18 | 19 | return min_rounds 20 | -------------------------------------------------------------------------------- /Python/Minimum Score Triangulation of Polygon.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n^2) 8 | Memory: O(n^2) 9 | """ 10 | 11 | def minScoreTriangulation(self, values: List[int]) -> int: 12 | @lru_cache(maxsize=None) 13 | def dp(i: int, j: int) -> int: 14 | if i + 1 >= j: 15 | return 0 16 | return min( 17 | dp(i, k) + dp(k, j) + values[i] * values[k] * values[j] 18 | for k in range(i + 1, j) 19 | ) 20 | 21 | return dp(0, len(values) - 1) 22 | -------------------------------------------------------------------------------- /Python/Minimum Size Subarray Sum.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(1) 9 | """ 10 | 11 | def minSubArrayLen(self, target: int, nums: List[int]) -> int: 12 | min_len = maxsize 13 | window_sum = start = 0 14 | 15 | for end, num in enumerate(nums): 16 | window_sum += num 17 | while window_sum >= target: 18 | min_len = min(min_len, end - start + 1) 19 | window_sum -= nums[start] 20 | start += 1 21 | 22 | return min_len if min_len != maxsize else 0 23 | -------------------------------------------------------------------------------- /Python/Minimum Time to Make Rope Colorful.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def minCost(self, colors: str, needed_time: List[int]) -> int: 11 | total_cost = color_cost = max_color_cost = 0 12 | prev_color = '*' 13 | 14 | for color, time in zip(colors, needed_time): 15 | if color == prev_color: 16 | color_cost += time 17 | max_color_cost = max(max_color_cost, time) 18 | else: 19 | total_cost += color_cost - max_color_cost 20 | color_cost = max_color_cost = time 21 | prev_color = color 22 | 23 | return total_cost + (color_cost - max_color_cost) 24 | -------------------------------------------------------------------------------- /Python/Monotonic Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def isMonotonic(self, nums: List[int]) -> bool: 11 | increasing = decreasing = True 12 | 13 | for i in range(len(nums) - 1): 14 | if increasing and nums[i] > nums[i + 1]: 15 | increasing = False 16 | if decreasing and nums[i] < nums[i + 1]: 17 | decreasing = False 18 | 19 | return increasing or decreasing 20 | -------------------------------------------------------------------------------- /Python/Most Frequent Even Element.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def mostFrequentEven(self, nums: List[int]) -> int: 12 | even_nums = (n for n in nums if not n & 1) 13 | count = Counter(even_nums) 14 | return max(count, key=lambda x: (count[x], -x)) if count else -1 15 | -------------------------------------------------------------------------------- /Python/Move Zeroes.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def moveZeroes(self, nums: List[int]) -> None: 11 | last_non_zero = 0 12 | for cur, num in enumerate(nums): 13 | if num != 0: 14 | nums[cur], nums[last_non_zero] = nums[last_non_zero], num 15 | last_non_zero += 1 16 | -------------------------------------------------------------------------------- /Python/N-th Tribonacci Number.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | @lru_cache(maxsize=None) 11 | def tribonacci(self, n: int) -> int: 12 | if n < 1: 13 | return 0 14 | if n < 3: 15 | return 1 16 | return self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3) 17 | 18 | 19 | class Solution: 20 | """ 21 | Time: O(n) 22 | Memory: O(1) 23 | """ 24 | 25 | def tribonacci(self, n: int) -> int: 26 | a, b, c = 0, 1, 1 27 | for _ in range(n): 28 | a, b, c = b, c, a + b + c 29 | return a 30 | 31 | -------------------------------------------------------------------------------- /Python/Nim Game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | def canWinNim(self, n: int) -> bool: 8 | return n % 4 != 0 9 | -------------------------------------------------------------------------------- /Python/Node With Highest Edge Score.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def edgeScore(self, edges: List[int]) -> int: 12 | score = defaultdict(int) 13 | 14 | for u, v in enumerate(edges): 15 | score[v] += u 16 | 17 | return max(score, key=lambda x: (score[x], -x)) 18 | -------------------------------------------------------------------------------- /Python/Non-decreasing Subsequences.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n^2) 7 | Memory: O(n^2) 8 | """ 9 | 10 | def findSubsequences(self, nums: List[int]) -> List[List[int]]: 11 | subs = {()} 12 | for num in nums: 13 | subs |= {sub + (num,) for sub in subs if not sub or sub[-1] <= num} 14 | return [sub for sub in subs if len(sub) >= 2] 15 | -------------------------------------------------------------------------------- /Python/Number of 1 Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log10(n)) 4 | Memory: O(1) 5 | """ 6 | 7 | MAX_BITS = 32 8 | 9 | def hammingWeight(self, n: int) -> int: 10 | return sum((n >> bit) & 1 for bit in range(self.MAX_BITS)) 11 | 12 | 13 | class Solution: 14 | """ 15 | Time: O(log10(n)) 16 | Memory: O(1) 17 | """ 18 | 19 | def hammingWeight(self, n: int) -> int: 20 | return n.bit_count() 21 | -------------------------------------------------------------------------------- /Python/Number of Common Factors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(min(n,m)) 4 | Memory: O(1) 5 | """ 6 | 7 | def commonFactors(self, n: int, m: int) -> int: 8 | return sum(not (n % i or m % i) for i in range(1, min(n, m) + 1)) 9 | -------------------------------------------------------------------------------- /Python/Number of Dice Rolls With Target Sum.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*k) 7 | Memory: O(n*k) 8 | """ 9 | 10 | MOD = 10 ** 9 + 7 11 | 12 | def numRollsToTarget(self, n: int, k: int, target: int) -> int: 13 | @lru_cache(None) 14 | def dp(d: int, t: int) -> int: 15 | if d == 0: 16 | return int(t == 0) 17 | return sum(dp(d - 1, t - i) for i in range(1, k + 1)) % self.MOD 18 | 19 | return dp(n, target) 20 | -------------------------------------------------------------------------------- /Python/Number of Subarrays With GCD Equal to K.py: -------------------------------------------------------------------------------- 1 | from math import gcd 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n^2*log(m)) 8 | Memory: O(1) 9 | 10 | where m - maximum number in nums 11 | """ 12 | 13 | def subarrayGCD(self, nums: List[int], k: int) -> int: 14 | n = len(nums) 15 | sub_arrays = 0 16 | 17 | for i in range(n): 18 | curr_gcd = 0 19 | for j in range(i, n): 20 | curr_gcd = gcd(curr_gcd, nums[j]) 21 | 22 | if curr_gcd == k: 23 | sub_arrays += 1 24 | elif curr_gcd < k or curr_gcd % k: 25 | break 26 | 27 | return sub_arrays 28 | -------------------------------------------------------------------------------- /Python/Number of Substrings With Only 1s.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | MOD = 10 ** 9 + 7 8 | 9 | def numSub(self, s: str) -> int: 10 | num = ones = 0 11 | 12 | for c in s: 13 | ones = ones + 1 if c == '1' else 0 14 | num = (num + ones) % self.MOD 15 | 16 | return num 17 | -------------------------------------------------------------------------------- /Python/Number of Zero-Filled Subarrays.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def zeroFilledSubarray(self, nums: List[int]) -> int: 11 | sub_arrays = l = 0 12 | 13 | for r, num in enumerate(nums): 14 | if num != 0: 15 | l = r + 1 16 | sub_arrays += r - l + 1 17 | 18 | return sub_arrays 19 | -------------------------------------------------------------------------------- /Python/Pairs of Songs With Total Durations Divisible by 60.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(1) 9 | """ 10 | 11 | def numPairsDivisibleBy60(self, time: List[int]) -> int: 12 | memo = defaultdict(int) 13 | count = 0 14 | 15 | for t in time: 16 | count += memo[-t % 60] 17 | memo[t % 60] += 1 18 | 19 | return count 20 | -------------------------------------------------------------------------------- /Python/Partition Array Such That Maximum Difference Is K.py: -------------------------------------------------------------------------------- 1 | from sys import maxsize 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(n)) 8 | Memory: O(1) 9 | """ 10 | 11 | def partitionArray(self, nums: List[int], k: int) -> int: 12 | nums.sort() 13 | start = -maxsize 14 | partitions = 0 15 | 16 | for num in nums: 17 | if num - start > k: 18 | start = num 19 | partitions += 1 20 | 21 | return partitions 22 | -------------------------------------------------------------------------------- /Python/Partition String Into Substrings With Values at Most K.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def minimumPartition(self, s: str, k: int) -> int: 8 | partitions = 1 9 | num = 0 10 | 11 | for d in map(int, s): 12 | num = 10 * num + d 13 | 14 | if num > k: 15 | partitions += 1 16 | num = d 17 | 18 | if num > k: 19 | return -1 20 | 21 | return partitions 22 | -------------------------------------------------------------------------------- /Python/Path Crossing.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | MOVES = { 8 | 'N': lambda x, y: (x, y + 1), 9 | 'S': lambda x, y: (x, y - 1), 10 | 'E': lambda x, y: (x + 1, y), 11 | 'W': lambda x, y: (x - 1, y), 12 | } 13 | 14 | def isPathCrossing(self, path: str) -> bool: 15 | x = y = 0 16 | seen = {(x, y)} 17 | 18 | for move in path: 19 | x, y = self.MOVES[move](x, y) 20 | if (x, y) in seen: 21 | return True 22 | seen.add((x, y)) 23 | 24 | return False 25 | -------------------------------------------------------------------------------- /Python/Path In Zigzag Labelled Binary Tree.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(log(n)) 7 | Memory: O(1) 8 | """ 9 | 10 | def pathInZigZagTree(self, label: int) -> List[int]: 11 | level = 0 12 | while 1 << level <= label: 13 | level += 1 14 | 15 | path = [-1] * level 16 | for i in range(level, 0, -1): 17 | path[i - 1] = label 18 | label = ((1 << i) - 1 - label + (1 << (i - 1))) // 2 19 | 20 | return path 21 | -------------------------------------------------------------------------------- /Python/Path Sum.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, val=0, left=None, right=None): 6 | self.val = val 7 | self.left = left 8 | self.right = right 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(n) 14 | Memory: O(n) 15 | """ 16 | 17 | def hasPathSum(self, root: Optional[TreeNode], target: int) -> bool: 18 | if root is None: 19 | return False 20 | if root.left is None and root.right is None: 21 | return target == root.val 22 | return self.hasPathSum( root.left, target - root.val) or \ 23 | self.hasPathSum(root.right, target - root.val) 24 | -------------------------------------------------------------------------------- /Python/Percentage of Letter in String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def percentageLetter(self, s: str, letter: str) -> int: 8 | return int(s.count(letter) / len(s) * 100) 9 | -------------------------------------------------------------------------------- /Python/Perfect Squares.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | from math import isqrt 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*√n) 8 | Memory: O(n) 9 | """ 10 | 11 | def numSquares(self, n: int) -> int: 12 | return self._decompose(n) 13 | 14 | @classmethod 15 | @lru_cache(None) 16 | def _decompose(cls, n: int) -> int: 17 | if n < 2: 18 | return n 19 | return 1 + min(cls._decompose(n - i * i) for i in range(1, isqrt(n) + 1)) 20 | -------------------------------------------------------------------------------- /Python/Positions of Large Groups.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | MIN_GROUP_LENGTH = 3 11 | 12 | def largeGroupPositions(self, s: str) -> List[List[int]]: 13 | positions = [] 14 | n = len(s) 15 | j = 0 16 | 17 | for i in range(n): 18 | if i == n - 1 or s[i] != s[i + 1]: 19 | if i - j + 1 >= self.MIN_GROUP_LENGTH: 20 | positions.append([j, i]) 21 | j = i + 1 22 | 23 | return positions 24 | -------------------------------------------------------------------------------- /Python/Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log(n)) 4 | Memory: O(1) 5 | """ 6 | 7 | def myPow(self, x: int, n: int) -> float: 8 | return x ** n 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(log(n)) 14 | Memory: O(log(n)) 15 | """ 16 | 17 | def myPow(self, x: int, n: int) -> float: 18 | if n == 0: 19 | return 1 20 | 21 | if n < 0: 22 | return 1 / self.myPow(x, -n) 23 | 24 | if n & 1: 25 | return x * self.myPow(x, n - 1) 26 | 27 | return self.myPow(x * x, n // 2) 28 | -------------------------------------------------------------------------------- /Python/Power of Four.py: -------------------------------------------------------------------------------- 1 | from math import log 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(log(n)) 7 | Memory: O(1) 8 | """ 9 | 10 | def isPowerOfFour(self, n: int) -> bool: 11 | return n > 0 and log(n, 4).is_integer() 12 | 13 | 14 | class Solution: 15 | """ 16 | Time: O(1) 17 | Memory: O(1) 18 | """ 19 | 20 | POWERS = {4 ** n for n in range(16)} 21 | 22 | def isPowerOfFour(self, n: int) -> bool: 23 | return n in self.POWERS 24 | -------------------------------------------------------------------------------- /Python/Power of Three.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | def isPowerOfThree(self, num: int) -> bool: 8 | return num > 0 and not 1162261467 % num 9 | -------------------------------------------------------------------------------- /Python/Range Addition II.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def maxCount(self, rows: int, cols: int, ops: List[List[int]]) -> int: 11 | if not ops: 12 | return rows * cols 13 | 14 | x, y = zip(*ops) 15 | return min(x) * min(y) 16 | 17 | 18 | class Solution: 19 | """ 20 | Time: O(n) 21 | Memory: O(1) 22 | """ 23 | 24 | def maxCount(self, rows: int, cols: int, ops: List[List[int]]) -> int: 25 | min_row = rows 26 | min_col = cols 27 | 28 | for row, col in ops: 29 | min_row = min(row, min_row) 30 | min_col = min(col, min_col) 31 | 32 | return min_row * min_col 33 | -------------------------------------------------------------------------------- /Python/Rank Transform of an Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log(n)) 7 | Memory: O(n) 8 | """ 9 | 10 | def arrayRankTransform(self, arr: List[int]) -> List[int]: 11 | ranks = {num: r for r, num in enumerate(sorted(set(arr)), start=1)} 12 | return [ranks[num] for num in arr] 13 | -------------------------------------------------------------------------------- /Python/Ransom Note.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n+m) 7 | Memory: O(n+m) 8 | """ 9 | 10 | def canConstruct(self, ransom_note: str, magazine: str) -> bool: 11 | return not Counter(ransom_note) - Counter(magazine) 12 | -------------------------------------------------------------------------------- /Python/Rectangle Area.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | def computeArea(self, *coords) -> int: 8 | x1, y1, x2, y2, x3, y3, x4, y4 = coords 9 | overlap = max(min(x2, x4) - max(x1, x3), 0) * max(min(y2, y4) - max(y1, y3), 0) 10 | return (x2 - x1) * (y2 - y1) + (x4 - x3) * (y4 - y3) - overlap 11 | -------------------------------------------------------------------------------- /Python/Rectangle Overlap.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(1) 7 | Memory: O(1) 8 | """ 9 | 10 | def isRectangleOverlap(self, rectangle_a: List[int], rectangle_b: List[int]) -> bool: 11 | x1, y1, x2, y2 = rectangle_a 12 | x3, y3, x4, y4 = rectangle_b 13 | return x1 < x4 and x3 < x2 and y1 < y4 and y3 < y2 14 | -------------------------------------------------------------------------------- /Python/Reduce Array Size to The Half.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(n)) 8 | Memory: O(n) 9 | """ 10 | 11 | def minSetSize(self, arr: List[int]) -> int: 12 | total_count = 0 13 | 14 | for index, count in enumerate(sorted(Counter(arr).values(), reverse=True)): 15 | total_count += count 16 | if total_count >= len(arr) // 2: 17 | return index + 1 18 | 19 | return 0 20 | -------------------------------------------------------------------------------- /Python/Relative Ranks.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log(n)) 7 | Memory: O(n) 8 | """ 9 | 10 | MEDALS = { 11 | 1: 'Gold Medal', 12 | 2: 'Silver Medal', 13 | 3: 'Bronze Medal', 14 | } 15 | 16 | def findRelativeRanks(self, nums: List[int]) -> List[str]: 17 | ranks = {num: ind for ind, num in enumerate(sorted(nums, reverse=True), start=1)} 18 | return [self._get_place(ranks[num]) for num in nums] 19 | 20 | @classmethod 21 | def _get_place(cls, place: int) -> str: 22 | return cls.MEDALS.get(place, str(place)) 23 | -------------------------------------------------------------------------------- /Python/Remove All Adjacent Duplicates In String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def removeDuplicates(self, string: str) -> str: 8 | stack = [] 9 | 10 | for c in string: 11 | if stack and c == stack[-1]: 12 | stack.pop() 13 | else: 14 | stack.append(c) 15 | 16 | return ''.join(stack) 17 | -------------------------------------------------------------------------------- /Python/Remove Duplicates from Sorted Array II.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | MAX_DUPLICATES = 2 11 | 12 | def removeDuplicates(self, nums: List[int]) -> int: 13 | i = 0 14 | 15 | for num in nums: 16 | if i < self.MAX_DUPLICATES or nums[i - self.MAX_DUPLICATES] != num: 17 | nums[i] = num 18 | i += 1 19 | 20 | return i 21 | -------------------------------------------------------------------------------- /Python/Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def removeDuplicates(self, nums: List[int]) -> int: 11 | pos = 0 12 | 13 | for i in range(len(nums)): 14 | if i == 0 or nums[i - 1] != nums[i]: 15 | nums[pos] = nums[i] 16 | pos += 1 17 | 18 | return pos 19 | -------------------------------------------------------------------------------- /Python/Remove Element.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def removeElement(self, nums: List[int], val: int) -> int: 11 | i = 0 12 | 13 | for num in nums: 14 | if num == val: 15 | continue 16 | nums[i] = num 17 | i += 1 18 | 19 | return i 20 | -------------------------------------------------------------------------------- /Python/Remove Nodes From Linked List.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | 10 | class Solution: 11 | """ 12 | Time: O(n) 13 | Memory: O(n) 14 | """ 15 | 16 | def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: 17 | if head is None: 18 | return None 19 | 20 | head.next = self.removeNodes(head.next) 21 | 22 | if head.next is not None and head.val < head.next.val: 23 | head = head.next 24 | 25 | return head 26 | -------------------------------------------------------------------------------- /Python/Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | 10 | class Solution: 11 | """ 12 | Time: O(n) 13 | Memory: O(1) 14 | """ 15 | 16 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 17 | fast = slow = head 18 | 19 | for k in range(n): 20 | fast = fast.next 21 | 22 | if fast is None: 23 | return head.next 24 | 25 | while fast.next: 26 | fast = fast.next 27 | slow = slow.next 28 | 29 | slow.next = slow.next.next 30 | 31 | return head 32 | -------------------------------------------------------------------------------- /Python/Remove Palindromic Subsequences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def removePalindromeSub(self, s: str) -> int: 8 | return 1 + (s != s[::-1]) 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(n) 14 | Memory: O(1) 15 | """ 16 | 17 | def removePalindromeSub(self, s: str) -> int: 18 | for i in range(len(s) // 2): 19 | if s[i] != s[-i - 1]: 20 | return 2 21 | return 1 22 | -------------------------------------------------------------------------------- /Python/Removing Stars From a String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def removeStars(self, string: str) -> str: 8 | stack = [] 9 | 10 | for c in string: 11 | if c == '*': 12 | if stack: 13 | stack.pop() 14 | else: 15 | stack.append(c) 16 | 17 | return ''.join(stack) 18 | -------------------------------------------------------------------------------- /Python/Reorder Routes to Make All Paths Lead to the City Zero.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def minReorder(self, n: int, connections: List[List[int]]) -> int: 12 | def dfs(curr: int, parent: int) -> int: 13 | return sum(cost + dfs(nei, curr) for nei, cost in graph[curr] if nei != parent) 14 | 15 | graph = defaultdict(list) 16 | for u, v in connections: 17 | graph[u].append((v, 1)) 18 | graph[v].append((u, 0)) 19 | 20 | return dfs(0, -1) 21 | -------------------------------------------------------------------------------- /Python/Reordered Power of 2.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(log(n)^2) 7 | Memory: O(log(n)) 8 | """ 9 | 10 | def reorderedPowerOf2(self, n: int) -> bool: 11 | digits = Counter(str(n)) 12 | return any(digits == Counter(str(1 << power)) for power in range(32)) 13 | -------------------------------------------------------------------------------- /Python/Replace All ?'s to Avoid Consecutive Repeating Characters.py: -------------------------------------------------------------------------------- 1 | from string import ascii_lowercase 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | REPLACEABLE = '?' 11 | 12 | def modifyString(self, s: str) -> str: 13 | s = list('#' + s + '#') 14 | 15 | for i, c in enumerate(s): 16 | if c == self.REPLACEABLE: 17 | s[i] = next(x for x in ascii_lowercase if s[i - 1] != x != s[i + 1]) 18 | 19 | return ''.join(s[1:-1]) 20 | -------------------------------------------------------------------------------- /Python/Reverse Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | MAS_BITS = 32 8 | 9 | def reverseBits(self, n: int) -> int: 10 | return sum(1 << (self.MAS_BITS - 1 - bit) for bit in range(self.MAS_BITS) if (n >> bit) & 1) 11 | 12 | 13 | class Solution: 14 | """ 15 | Time: O(1) 16 | Memory: O(1) 17 | """ 18 | 19 | def reverseBits(self, n: int) -> int: 20 | n = ((n & 0x55555555) << 1) | ((n & 0xAAAAAAAA) >> 1) 21 | n = ((n & 0x33333333) << 2) | ((n & 0xCCCCCCCC) >> 2) 22 | n = ((n & 0x0F0F0F0F) << 4) | ((n & 0xF0F0F0F0) >> 4) 23 | n = ((n & 0x00FF00FF) << 8) | ((n & 0xFF00FF00) >> 8) 24 | n = ((n & 0x0000FFFF) << 16) | ((n & 0xFFFF0000) >> 16) 25 | return n 26 | -------------------------------------------------------------------------------- /Python/Reverse Words in a String III.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def reverseWords(self, string: str) -> str: 8 | return ' '.join(word[::-1] for word in string.split()) 9 | 10 | -------------------------------------------------------------------------------- /Python/Reverse Words in a String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def reverseWords(self, s: str) -> str: 8 | return ' '.join(reversed(s.split())) 9 | -------------------------------------------------------------------------------- /Python/Richest Customer Wealth.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(1) 8 | """ 9 | 10 | def maximumWealth(self, accounts: List[List[int]]) -> int: 11 | return max(map(sum, accounts)) 12 | -------------------------------------------------------------------------------- /Python/Roman to Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | ROMAN_TO_INTEGER = { 8 | 'I': 1, 9 | 'IV': 4, 10 | 'V': 5, 11 | 'IX': 9, 12 | 'X': 10, 13 | 'XL': 40, 14 | 'L': 50, 15 | 'XC': 90, 16 | 'C': 100, 17 | 'CD': 400, 18 | 'D': 500, 19 | 'CM': 900, 20 | 'M': 1000, 21 | } 22 | 23 | def romanToInt(self, s: str) -> int: 24 | converted = 0 25 | 26 | for roman, integer in self.ROMAN_TO_INTEGER.items(): 27 | while s.endswith(roman): 28 | s = s.removesuffix(roman) 29 | converted += integer 30 | 31 | return converted -------------------------------------------------------------------------------- /Python/Rotate Image.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n^2) 7 | Memory: O(1) 8 | """ 9 | 10 | def rotate(self, mat: List[List[int]]) -> None: 11 | n = len(mat) 12 | for layer in range(n // 2): 13 | for i in range((n + 1) // 2): 14 | mat[layer][i], mat[i][n - layer - 1], mat[n - layer - 1][n - i - 1], mat[n - i - 1][layer] = \ 15 | mat[n - i - 1][layer], mat[layer][i], mat[i][n - layer - 1], mat[n - layer - 1][n - i - 1] 16 | -------------------------------------------------------------------------------- /Python/Rotate List.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class ListNode: 5 | def __init__(self, val=0, next=None): 6 | self.val = val 7 | self.next = next 8 | 9 | 10 | class Solution: 11 | """ 12 | Time: O(n) 13 | Memory: O(1) 14 | """ 15 | 16 | def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: 17 | if head is None: 18 | return None 19 | 20 | tail = head 21 | length = 1 22 | 23 | while tail.next: 24 | length += 1 25 | tail = tail.next 26 | 27 | tail.next = head 28 | k %= length 29 | 30 | for _ in range(length - k): 31 | tail = tail.next 32 | 33 | head, tail.next = tail.next, None 34 | return head 35 | -------------------------------------------------------------------------------- /Python/Rotated Digits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n*log10(n)) 4 | Memory: O(log10(n)) 5 | """ 6 | 7 | SINGLE = {'0', '1', '8'} 8 | PAIRED = {'2', '5', '6', '9'} 9 | ROTATABLE = SINGLE | PAIRED 10 | 11 | def rotatedDigits(self, n: int) -> int: 12 | return sum(map(self.is_good, range(n + 1))) 13 | 14 | @classmethod 15 | def is_good(cls, num: int) -> bool: 16 | digits = set(str(num)) 17 | return digits.issubset(cls.ROTATABLE) and not digits.issubset(cls.SINGLE) 18 | -------------------------------------------------------------------------------- /Python/Running Sum of 1d Array.py: -------------------------------------------------------------------------------- 1 | from itertools import accumulate 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def runningSum(self, nums: List[int]): 12 | return accumulate(nums) 13 | 14 | 15 | class Solution: 16 | """ 17 | Time: O(n) 18 | Memory: O(1) 19 | """ 20 | 21 | def runningSum(self, nums: List[int]) -> List[int]: 22 | for i in range(1, len(nums)): 23 | nums[i] += nums[i - 1] 24 | return nums 25 | -------------------------------------------------------------------------------- /Python/Same Tree.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | 4 | class TreeNode: 5 | def __init__(self, val=0, left=None, right=None): 6 | self.val = val 7 | self.left = left 8 | self.right = right 9 | 10 | 11 | class Solution: 12 | """ 13 | Time: O(n) 14 | Memory: O(H) 15 | """ 16 | 17 | def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 18 | if p is None or q is None: 19 | return p is None and q is None 20 | return p.val == q.val \ 21 | and self.isSameTree(p.left, q.left) \ 22 | and self.isSameTree(p.right, q.right) 23 | -------------------------------------------------------------------------------- /Python/Search a 2D Matrix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(log(n*m)) 7 | Memory: O(1) 8 | """ 9 | 10 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 11 | n, m = len(matrix), len(matrix[0]) 12 | left, right = 0, n * m - 1 13 | 14 | while left <= right: 15 | mid = (left + right) // 2 16 | num = matrix[mid // m][mid % m] 17 | 18 | if num == target: 19 | return True 20 | 21 | if num < target: 22 | left = mid + 1 23 | else: 24 | right = mid - 1 25 | 26 | return False 27 | -------------------------------------------------------------------------------- /Python/Set Matrix Zeroes.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(n+m) 8 | """ 9 | 10 | def setZeroes(self, matrix: List[List[int]]) -> None: 11 | n, m = len(matrix), len(matrix[0]) 12 | 13 | cols_to_set_zero = set() 14 | rows_to_set_zero = set() 15 | 16 | for row in range(n): 17 | for col in range(m): 18 | if matrix[row][col] == 0: 19 | rows_to_set_zero.add(row) 20 | cols_to_set_zero.add(col) 21 | 22 | for row in range(n): 23 | for col in range(m): 24 | if row in rows_to_set_zero or col in cols_to_set_zero: 25 | matrix[row][col] = 0 26 | -------------------------------------------------------------------------------- /Python/Set Mismatch.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def findErrorNums(self, nums: List[int]) -> List[int]: 11 | duplicate = -1 12 | missing = 1 13 | 14 | for n in nums: 15 | if nums[abs(n) - 1] < 0: 16 | duplicate = abs(n) 17 | else: 18 | nums[abs(n) - 1] *= -1 19 | 20 | for i in range(1, len(nums)): 21 | if nums[i] > 0: 22 | missing = i + 1 23 | 24 | return [duplicate, missing] 25 | -------------------------------------------------------------------------------- /Python/Shift 2D Grid.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n^2) 7 | Memory: O(n^2) 8 | """ 9 | 10 | def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: 11 | n, m = len(grid), len(grid[0]) 12 | size = n * m 13 | return [[grid[(i * m + j - k) % size // m][(i * m + j - k) % size % m] for j in range(m)] for i in range(n)] 14 | -------------------------------------------------------------------------------- /Python/Shortest Completing Word.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(m*max(n,k)) 8 | Memory: O(n+k) 9 | 10 | n - length of letters in license_plate 11 | m - length of words 12 | k - length of each word in words 13 | """ 14 | 15 | def shortestCompletingWord(self, license_plate: str, words: List[str]) -> str: 16 | letters = Counter(ltr.lower() for ltr in license_plate if ltr.isalpha()) 17 | return min((word for word in words if not letters - Counter(word)), key=len) 18 | -------------------------------------------------------------------------------- /Python/Shuffle the Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def shuffle(self, nums: List[int], n: int) -> List[int]: 11 | return [nums[j] for i in range(n) for j in (i, i + n)] 12 | -------------------------------------------------------------------------------- /Python/Simplify Path.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | SEP = '/' 8 | CURRENT_DIR = '.' 9 | PARENT_DIR = '..' 10 | 11 | def simplifyPath(self, path: str) -> str: 12 | simplified = [] 13 | 14 | for directory in path.split(self.SEP): 15 | if not directory or directory == self.CURRENT_DIR: 16 | continue 17 | 18 | if directory == self.PARENT_DIR: 19 | if simplified: 20 | simplified.pop() 21 | else: 22 | simplified.append(directory) 23 | 24 | return self.SEP + self.SEP.join(simplified) 25 | -------------------------------------------------------------------------------- /Python/Single Number.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | from operator import xor 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | """ 8 | Time: O(n) 9 | Memory: O(1) 10 | """ 11 | 12 | def singleNumber(self, nums: List[int]) -> int: 13 | return reduce(xor, nums) 14 | -------------------------------------------------------------------------------- /Python/Smallest Even Multiple.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(1) 4 | Memory: O(1) 5 | """ 6 | 7 | def smallestEvenMultiple(self, n: int) -> int: 8 | return n << (n & 1) 9 | -------------------------------------------------------------------------------- /Python/Smallest String With A Given Numeric Value.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def getSmallestString(self, n: int, k: int) -> str: 8 | s = [ord('a')] * n 9 | 10 | k = k - n 11 | for i in reversed(range(n)): 12 | if k < 25: 13 | s[i] += k 14 | break 15 | s[i] += 25 16 | k -= 25 17 | 18 | return ''.join(map(chr, s)) 19 | -------------------------------------------------------------------------------- /Python/Sort Integers by The Power Value.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log(n)) 7 | Memory: O(log(n)) 8 | """ 9 | 10 | def getKth(self, lo: int, hi: int, k: int) -> int: 11 | return sorted(range(lo, hi + 1), key=self.power)[k - 1] 12 | 13 | @classmethod 14 | @lru_cache(maxsize=None) 15 | def power(cls, n: int) -> int: 16 | if n == 1: 17 | return 1 18 | return cls.power(3 * n + 1 if n & 1 else n >> 1) + 1 19 | -------------------------------------------------------------------------------- /Python/Sort the People.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*log(n)) 7 | Memory: O(n) 8 | """ 9 | 10 | def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: 11 | return [name for _, name in sorted(zip(heights, names), reverse=True)] 12 | -------------------------------------------------------------------------------- /Python/Spiral Matrix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(?) 7 | Memory: O(?) 8 | """ 9 | 10 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 11 | if not matrix: 12 | return [] 13 | return matrix.pop(0) + self.spiralOrder(list(map(list, zip(*matrix)))[::-1]) 14 | -------------------------------------------------------------------------------- /Python/Strictly Palindromic Number.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyrylo-Ktl/LeetCode-Solutions/31e0264f803cdc61da9da6fd3a83109a76d216d5/Python/Strictly Palindromic Number.py -------------------------------------------------------------------------------- /Python/String Matching in an Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n^2*k^2) 7 | Memory: O(1) 8 | 9 | where k - the longest word length 10 | """ 11 | 12 | def stringMatching(self, words: List[str]) -> List[str]: 13 | words = sorted(words, key=len) 14 | result = [] 15 | 16 | for i in range(len(words)): 17 | for j in range(i + 1, len(words)): 18 | if words[i] in words[j]: 19 | result.append(words[i]) 20 | break 21 | 22 | return result 23 | -------------------------------------------------------------------------------- /Python/String to Integer (atoi).py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | NUMBER_REGEX = r'^[\+\-]?0*\d+' 11 | MAX_NUM = (1 << 31) - 1 12 | MIN_NUM = -(1 << 31) 13 | 14 | def myAtoi(self, s: str) -> int: 15 | numbers = re.search(self.NUMBER_REGEX, s.strip()) 16 | num = 0 if numbers is None else int(numbers.group(0)) 17 | return max(self.MIN_NUM, min(self.MAX_NUM, num)) 18 | -------------------------------------------------------------------------------- /Python/Strong Password Checker II.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | PATTERN = r'(?!.*(.)\1)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()+-]).{8,}' 11 | 12 | def strongPasswordCheckerII(self, password: str) -> bool: 13 | return re.fullmatch(self.PATTERN, password) is not None 14 | -------------------------------------------------------------------------------- /Python/Student Attendance Record I.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def checkRecord(self, s: str) -> bool: 8 | return s.count('A') < 2 and 'LLL' not in s 9 | -------------------------------------------------------------------------------- /Python/Subarray Sum Equals K.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def subarraySum(self, nums: List[int], k: int) -> int: 11 | prefix_sum = {0: 1} 12 | cum_sum = subarrays = 0 13 | 14 | for num in nums: 15 | cum_sum += num 16 | if cum_sum - k in prefix_sum: 17 | subarrays += prefix_sum[cum_sum - k] 18 | prefix_sum[cum_sum] = prefix_sum.get(cum_sum, 0) + 1 19 | 20 | return subarrays 21 | -------------------------------------------------------------------------------- /Python/Subdomain Visit Count.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*k) 8 | Memory: O(n*k) 9 | 10 | where k - maximum number of subdomains 11 | """ 12 | 13 | def subdomainVisits(self, domains: List[str]) -> List[str]: 14 | ans = defaultdict(int) 15 | 16 | for domain in domains: 17 | count, domain = domain.split() 18 | count = int(count) 19 | 20 | sub_domains = domain.split('.') 21 | for i in range(len(sub_domains)): 22 | ans['.'.join(sub_domains[i:])] += count 23 | 24 | return ['{} {}'.format(cnt, dom) for dom, cnt in ans.items()] 25 | -------------------------------------------------------------------------------- /Python/Substrings of Size Three with Distinct Characters.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(min(k, n)) 8 | """ 9 | 10 | K = 3 11 | 12 | def countGoodSubstrings(self, s: str) -> int: 13 | window = Counter(s[:self.K]) 14 | count = int(len(window) == self.K) 15 | 16 | for i in range(self.K, len(s)): 17 | if window[s[i - self.K]] > 1: 18 | window[s[i - self.K]] -= 1 19 | else: 20 | window.pop(s[i - self.K]) 21 | window[s[i]] += 1 22 | 23 | count += int(len(window) == self.K) 24 | 25 | return count 26 | -------------------------------------------------------------------------------- /Python/Sum of Digits of String After Convert.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def getLucky(self, s: str, k: int) -> int: 8 | num = self.to_number(s) 9 | 10 | while k > 0 and num >= 10: 11 | num = self.sum_digits(num) 12 | k -= 1 13 | 14 | return num 15 | 16 | @staticmethod 17 | def to_number(s: str) -> int: 18 | return int(''.join(str(ord(c) - ord('a') + 1) for c in s)) 19 | 20 | @staticmethod 21 | def sum_digits(num: int) -> int: 22 | return sum(int(d) for d in str(num)) 23 | -------------------------------------------------------------------------------- /Python/Target Sum.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*t) 8 | Memory: O(n*t) 9 | 10 | where t - sum of nums list 11 | """ 12 | 13 | def findTargetSumWays(self, nums: List[int], target: int) -> int: 14 | @lru_cache(None) 15 | def dp(i: int, curr_sum: int) -> int: 16 | if i < 0: 17 | return int(curr_sum == target) 18 | return dp(i - 1, curr_sum - nums[i]) + \ 19 | dp(i - 1, curr_sum + nums[i]) 20 | 21 | return dp(len(nums) - 1, 0) 22 | -------------------------------------------------------------------------------- /Python/The Employee That Worked on the Longest Task.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def hardestWorker(self, n: int, logs: List[List[int]]) -> int: 11 | best_id = best_time = start = 0 12 | 13 | for emp_id, end in logs: 14 | time = end - start 15 | if time > best_time or (time == best_time and best_id > emp_id): 16 | best_id = emp_id 17 | best_time = time 18 | start = end 19 | 20 | return best_id 21 | -------------------------------------------------------------------------------- /Python/The Number of Weak Characters in the Game.py: -------------------------------------------------------------------------------- 1 | from itertools import groupby 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n*log(n)) 8 | Memory: O(n) 9 | """ 10 | 11 | def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: 12 | properties.sort(reverse=True) 13 | max_defence = weak = 0 14 | 15 | for _, group in groupby(properties, key=lambda x: x[0]): 16 | defences = [d for _, d in group] 17 | weak += sum(d < max_defence for d in defences) 18 | max_defence = max(max_defence, max(defences)) 19 | 20 | return weak 21 | -------------------------------------------------------------------------------- /Python/Time Needed to Inform All Employees.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def numOfMinutes(self, n: int, head_id: int, manager: List[int], inform_time: List[int]) -> int: 12 | def dfs(boss: int) -> int: 13 | return inform_time[boss] + max((dfs(emp) for emp in subordinates[boss]), default=0) 14 | 15 | subordinates = defaultdict(set) 16 | 17 | for u, v in enumerate(manager): 18 | subordinates[v].add(u) 19 | 20 | return dfs(head_id) 21 | -------------------------------------------------------------------------------- /Python/Time Needed to Rearrange a Binary String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def secondsToRemoveOccurrences(self, s: str) -> int: 8 | seconds = zeros = 0 9 | 10 | for c in s: 11 | zeros += c == '0' 12 | if c == '1' and zeros > 0: 13 | seconds = max(seconds + 1, zeros) 14 | 15 | return seconds 16 | -------------------------------------------------------------------------------- /Python/Top K Frequent Words.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import heapq 3 | from typing import List 4 | 5 | 6 | class Solution: 7 | """ 8 | Time: O(n*log(n)) 9 | Memory: O(n) 10 | """ 11 | 12 | def topKFrequent(self, words: List[str], k: int) -> List[str]: 13 | freq = collections.Counter(words) 14 | return heapq.nsmallest(k, freq, key=lambda word: (-freq[word], word)) 15 | -------------------------------------------------------------------------------- /Python/Transpose Matrix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n*m) 7 | Memory: O(1) 8 | """ 9 | 10 | def transpose(self, matrix: List[List[int]]) -> List[List[int]]: 11 | n, m = len(matrix), len(matrix[0]) 12 | return [[matrix[i][j] for i in range(n)] for j in range(m)] 13 | 14 | 15 | class Solution: 16 | """ 17 | Time: O(n*m) 18 | Memory: O(1) 19 | """ 20 | 21 | def transpose(self, matrix: List[List[int]]) -> List[List[int]]: 22 | return zip(*matrix) 23 | -------------------------------------------------------------------------------- /Python/Trapping Rain Water.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def trap(self, height: List[int]) -> int: 11 | n = len(height) 12 | 13 | left_max = [0] * n 14 | left_max[0] = height[0] 15 | for i in range(1, n): 16 | left_max[i] = max(height[i], left_max[i - 1]) 17 | 18 | right_max = [0] * n 19 | right_max[-1] = height[-1] 20 | for i in reversed(range(0, n - 1)): 21 | right_max[i] = max(height[i], right_max[i + 1]) 22 | 23 | return sum(min(l_max, r_max) - h for h, l_max, r_max in zip(height, left_max, right_max)) 24 | -------------------------------------------------------------------------------- /Python/Triples with Bitwise AND Equal To Zero.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n^3) 8 | Memory: O(n^2) 9 | """ 10 | 11 | def countTriplets(self, nums: List[int]) -> int: 12 | count = Counter(x & y for x in nums for y in nums) 13 | return sum(cnt for xy, cnt in count.items() for z in nums if not xy & z) 14 | -------------------------------------------------------------------------------- /Python/Two Furthest Houses With Different Colors.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(1) 8 | """ 9 | 10 | def maxDistance(self, colors: List[int]) -> int: 11 | max_dist = 0 12 | 13 | for i, x in enumerate(colors): 14 | if x != colors[0]: 15 | max_dist = max(max_dist, i) 16 | if x != colors[-1]: 17 | max_dist = max(max_dist, len(colors) - 1 - i) 18 | 19 | return max_dist 20 | -------------------------------------------------------------------------------- /Python/Two Sum.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 11 | index = {} 12 | for i, num in enumerate(numbers): 13 | if target - num in index: 14 | return [index[target - num], i] 15 | index[num] = i 16 | -------------------------------------------------------------------------------- /Python/Ugly Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(log(n)) 4 | Memory: O(1) 5 | """ 6 | 7 | def isUgly(self, n: int) -> bool: 8 | while n > 1: 9 | if not n % 5: 10 | n //= 5 11 | elif not n % 3: 12 | n //= 3 13 | elif not n % 2: 14 | n //= 2 15 | else: 16 | return False 17 | 18 | return n > 0 19 | -------------------------------------------------------------------------------- /Python/Unique Number of Occurrences.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | """ 7 | Time: O(n) 8 | Memory: O(n) 9 | """ 10 | 11 | def uniqueOccurrences(self, arr: List[int]) -> bool: 12 | return len(set(arr)) == len(set(Counter(arr).values())) 13 | -------------------------------------------------------------------------------- /Python/Valid Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(1) 5 | """ 6 | 7 | def isPalindrome(self, s: str) -> bool: 8 | left, right = 0, len(s) - 1 9 | 10 | while left < right: 11 | if not s[left].isalnum(): 12 | left += 1 13 | elif not s[right].isalnum(): 14 | right -= 1 15 | elif s[left].lower() != s[right].lower(): 16 | return False 17 | else: 18 | left += 1 19 | right -= 1 20 | 21 | return True 22 | -------------------------------------------------------------------------------- /Python/Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | OPPOSITE = {'(': ')', '[': ']', '{': '}'} 8 | 9 | def isValid(self, string: str) -> bool: 10 | stack = [] 11 | 12 | for bracket in string: 13 | if bracket in self.OPPOSITE: 14 | stack.append(bracket) 15 | elif not stack or bracket != self.OPPOSITE[stack[-1]]: 16 | return False 17 | else: 18 | stack.pop() 19 | 20 | return not stack 21 | -------------------------------------------------------------------------------- /Python/Validate IP Address.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(1) 7 | Memory: O(1) 8 | """ 9 | 10 | IPv4 = r'([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])' 11 | IPv4_PATTERN = re.compile(rf'{IPv4}\.{IPv4}\.{IPv4}\.{IPv4}') 12 | 13 | IPv6 = r'([0-9a-fA-F]{1,4})' 14 | IPv6_PATTERN = re.compile(rf'{IPv6}\:{IPv6}\:{IPv6}\:{IPv6}\:{IPv6}\:{IPv6}\:{IPv6}\:{IPv6}') 15 | 16 | def validIPAddress(self, address: str) -> str: 17 | return { 18 | self.IPv4_PATTERN.fullmatch(address) is not None: 'IPv4', 19 | self.IPv6_PATTERN.fullmatch(address) is not None: 'IPv6', 20 | }.get(True, 'Neither') 21 | -------------------------------------------------------------------------------- /Python/Validate Stack Sequences.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(n) 7 | Memory: O(n) 8 | """ 9 | 10 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: 11 | stack = [] 12 | 13 | for i in pushed: 14 | stack.append(i) 15 | while stack and popped and stack[-1] == popped[0]: 16 | stack.pop() 17 | popped.pop(0) 18 | 19 | return not stack 20 | -------------------------------------------------------------------------------- /Python/Water and Jug Problem.py: -------------------------------------------------------------------------------- 1 | from math import gcd 2 | 3 | 4 | class Solution: 5 | """ 6 | Time: O(log2(max(n,m))) 7 | Memory: O(log2(max(n,m))) 8 | 9 | where n - first_jug, 10 | m - second_jug 11 | """ 12 | 13 | def canMeasureWater(self, first_jug: int, second_jug: int, target: int) -> bool: 14 | if first_jug + second_jug < target: 15 | return False 16 | if first_jug == target or second_jug == target: 17 | return True 18 | return not target % gcd(first_jug, second_jug) 19 | -------------------------------------------------------------------------------- /Python/Word Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def wordPattern(self, pattern: str, string: str) -> bool: 8 | words = string.split() 9 | 10 | if len(words) != len(pattern): 11 | return False 12 | 13 | pattern_map = {} 14 | string_map = {} 15 | 16 | for p, w in zip(pattern, words): 17 | if pattern_map.setdefault(p, w) != w or string_map.setdefault(w, p) != p: 18 | return False 19 | 20 | return True 21 | -------------------------------------------------------------------------------- /Python/Zigzag Conversion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | Time: O(n) 4 | Memory: O(n) 5 | """ 6 | 7 | def convert(self, string: str, n_rows: int) -> str: 8 | if n_rows == 1: 9 | return string 10 | 11 | rows = [''] * n_rows 12 | turn = -1 13 | curr_level = 0 14 | 15 | for i, c in enumerate(string): 16 | if not i % (n_rows - 1): 17 | turn *= -1 18 | rows[curr_level] += c 19 | curr_level += turn 20 | 21 | return ''.join(rows) 22 | -------------------------------------------------------------------------------- /SQL/Actors and Directors Who Cooperated At Least Three Times.sql: -------------------------------------------------------------------------------- 1 | SELECT actor_id, 2 | director_id 3 | FROM ActorDirector 4 | GROUP BY actor_id, director_id 5 | HAVING COUNT(*) >= 3; 6 | -------------------------------------------------------------------------------- /SQL/Article Views I.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT author_id AS id 2 | FROM Views 3 | WHERE author_id = viewer_id 4 | ORDER BY id; 5 | -------------------------------------------------------------------------------- /SQL/Bank Account Summary II.sql: -------------------------------------------------------------------------------- 1 | SELECT u.name, 2 | SUM(t.amount) AS balance 3 | FROM Users AS u LEFT JOIN Transactions AS t 4 | ON u.account = t.account 5 | GROUP BY u.name 6 | HAVING SUM(t.amount) >= 10000; 7 | -------------------------------------------------------------------------------- /SQL/Big Countries.sql: -------------------------------------------------------------------------------- 1 | SELECT name, 2 | population, 3 | area 4 | FROM World 5 | WHERE population >= 25000000 6 | OR area >= 3000000; 7 | -------------------------------------------------------------------------------- /SQL/Calculate Special Bonus.sql: -------------------------------------------------------------------------------- 1 | SELECT employee_id, 2 | IF (employee_id % 2 != 0 AND name NOT LIKE 'M%', salary, 0) AS bonus 3 | FROM Employees 4 | ORDER BY employee_id; 5 | -------------------------------------------------------------------------------- /SQL/Capital Gain%Loss.sql: -------------------------------------------------------------------------------- 1 | SELECT stock_name, 2 | SUM(IF(operation='Buy', -price, price)) AS capital_gain_loss 3 | FROM Stocks 4 | GROUP BY stock_name; 5 | -------------------------------------------------------------------------------- /SQL/Classes More Than 5 Students.sql: -------------------------------------------------------------------------------- 1 | SELECT class 2 | FROM Courses 3 | GROUP BY class 4 | HAVING COUNT(*) >= 5; -------------------------------------------------------------------------------- /SQL/Combine Two Tables.sql: -------------------------------------------------------------------------------- 1 | SELECT FirstName, 2 | LastName, 3 | City, 4 | State 5 | FROM Person AS p LEFT JOIN Address AS a 6 | ON p.PersonId = a.PersonId; 7 | -------------------------------------------------------------------------------- /SQL/Consecutive Numbers.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT l1.Num AS ConsecutiveNums 2 | FROM Logs l1, 3 | Logs l2, 4 | Logs l3 5 | WHERE l1.Id = l2.Id - 1 6 | AND l2.Id = l3.Id - 1 7 | AND l1.Num = l2.Num 8 | AND l2.Num = l3.Num; 9 | -------------------------------------------------------------------------------- /SQL/Customer Placing the Largest Number of Orders.sql: -------------------------------------------------------------------------------- 1 | SELECT customer_number 2 | FROM Orders 3 | GROUP BY customer_number 4 | ORDER BY COUNT(*) DESC 5 | LIMIT 1; 6 | -------------------------------------------------------------------------------- /SQL/Customer Who Visited but Did Not Make Any Transactions.sql: -------------------------------------------------------------------------------- 1 | SELECT v.customer_id, 2 | COUNT(*) AS count_no_trans 3 | FROM Visits AS v LEFT JOIN Transactions AS t 4 | ON v.visit_id = t.visit_id 5 | WHERE t.visit_id IS NULL 6 | GROUP BY customer_id; 7 | -------------------------------------------------------------------------------- /SQL/Customers Who Never Order.sql: -------------------------------------------------------------------------------- 1 | SELECT name AS 'Customers' 2 | FROM Customers 3 | WHERE id NOT IN ( 4 | SELECT customerId 5 | FROM Orders 6 | ); 7 | -------------------------------------------------------------------------------- /SQL/Daily Leads and Partners.sql: -------------------------------------------------------------------------------- 1 | SELECT date_id, 2 | make_name, 3 | COUNT(DISTINCT lead_id) AS unique_leads, 4 | COUNT(DISTINCT partner_id) AS unique_partners 5 | FROM DailySales 6 | GROUP BY date_id, make_name; 7 | -------------------------------------------------------------------------------- /SQL/Delete Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | DELETE p1 2 | FROM Person p1, 3 | Person p2 4 | WHERE p1.Email = p2.Email 5 | AND p1.Id > p2.Id; 6 | -------------------------------------------------------------------------------- /SQL/Department Highest Salary.sql: -------------------------------------------------------------------------------- 1 | SELECT department, 2 | employee, 3 | salary 4 | FROM ( 5 | SELECT d.name AS department, 6 | e.name AS employee, 7 | e.salary, 8 | MAX(e.salary) OVER (PARTITION BY d.id) AS max_salary 9 | FROM Employee e JOIN Department d 10 | ON e.departmentId = d.id 11 | ) AS _ 12 | WHERE salary = max_salary; -------------------------------------------------------------------------------- /SQL/Department Top Three Salaries.sql: -------------------------------------------------------------------------------- 1 | SELECT d.Name AS Department, 2 | a.Name AS Employee, 3 | a.Salary 4 | FROM ( 5 | SELECT e.*, 6 | DENSE_RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS DepSalRank 7 | FROM Employee e 8 | ) a JOIN Department d 9 | ON a.DepartmentId = d. Id 10 | WHERE DepSalRank <= 3; 11 | -------------------------------------------------------------------------------- /SQL/Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | SELECT email 2 | FROM Person 3 | GROUP BY email 4 | HAVING COUNT(*) > 1; 5 | -------------------------------------------------------------------------------- /SQL/Employees Earning More Than Their Managers.sql: -------------------------------------------------------------------------------- 1 | SELECT emp.name AS Employee 2 | FROM Employee emp JOIN Employee man 3 | ON emp.managerId = man.id 4 | WHERE emp.salary > man.salary; 5 | -------------------------------------------------------------------------------- /SQL/Employees With Missing Information.sql: -------------------------------------------------------------------------------- 1 | WITH Emp AS ( 2 | SELECT * 3 | FROM Employees LEFT JOIN Salaries USING (employee_id) 4 | UNION 5 | SELECT * 6 | FROM Employees RIGHT JOIN Salaries USING (employee_id) 7 | ) 8 | 9 | SELECT employee_id 10 | FROM Emp 11 | WHERE salary IS NULL 12 | OR name IS NULL 13 | ORDER BY employee_id; 14 | -------------------------------------------------------------------------------- /SQL/Find Customer Referee.sql: -------------------------------------------------------------------------------- 1 | SELECT name 2 | FROM Customer 3 | WHERE referee_id != 2 4 | OR referee_id IS NULL; 5 | -------------------------------------------------------------------------------- /SQL/Find Followers Count.sql: -------------------------------------------------------------------------------- 1 | SELECT user_id, 2 | COUNT(follower_id) AS followers_count 3 | FROM Followers 4 | GROUP BY user_id 5 | ORDER BY user_id; 6 | -------------------------------------------------------------------------------- /SQL/Find Total Time Spent by Each Employee.sql: -------------------------------------------------------------------------------- 1 | SELECT event_day AS day, 2 | emp_id, 3 | SUM(out_time - in_time) AS total_time 4 | FROM Employees 5 | GROUP BY emp_id, event_day; 6 | -------------------------------------------------------------------------------- /SQL/Fix Names in a Table.sql: -------------------------------------------------------------------------------- 1 | SELECT user_id, 2 | CONCAT(UPPER(SUBSTRING(name, 1, 1)), 3 | LOWER(SUBSTRING(name, 2))) AS name 4 | FROM Users 5 | ORDER BY user_id; 6 | -------------------------------------------------------------------------------- /SQL/Game Play Analysis I.sql: -------------------------------------------------------------------------------- 1 | SELECT player_id, 2 | MIN(event_date) AS first_login 3 | FROM Activity 4 | GROUP BY player_id 5 | ORDER BY player_id; 6 | -------------------------------------------------------------------------------- /SQL/Group Sold Products By The Date.sql: -------------------------------------------------------------------------------- 1 | SELECT sell_date, 2 | COUNT(DISTINCT product) AS num_sold, 3 | GROUP_CONCAT(DISTINCT product ORDER BY product ASC SEPARATOR ',') products 4 | FROM activities 5 | GROUP BY sell_date 6 | ORDER BY sell_date; 7 | -------------------------------------------------------------------------------- /SQL/Market Analysis I.sql: -------------------------------------------------------------------------------- 1 | SELECT u.user_id AS buyer_id, 2 | join_date, 3 | COALESCE(COUNT(order_date), 0) AS orders_in_2019 4 | FROM Users AS u LEFT JOIN Orders o 5 | ON u.user_id = o.buyer_id AND YEAR(order_date) = '2019' 6 | GROUP BY u.user_id; 7 | -------------------------------------------------------------------------------- /SQL/Not Boring Movies.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Cinema 3 | WHERE id % 2 = 1 AND description != "boring" 4 | ORDER BY rating DESC; 5 | -------------------------------------------------------------------------------- /SQL/Nth Highest Salary.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 | BEGIN 3 | SET N = N - 1; 4 | RETURN ( 5 | SELECT DISTINCT(salary) 6 | FROM Employee 7 | ORDER BY salary DESC 8 | LIMIT 1 9 | OFFSET N 10 | ); 11 | END 12 | -------------------------------------------------------------------------------- /SQL/Patients With a Condition.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM Patients 3 | WHERE conditions REGEXP '\\bDIAB1'; 4 | -------------------------------------------------------------------------------- /SQL/Rank Scores.sql: -------------------------------------------------------------------------------- 1 | SELECT s1.score, 2 | COUNT(s2.score) AS "Rank" 3 | FROM Scores s1, 4 | (SELECT DISTINCT score FROM Scores) s2 5 | WHERE s1.score <= s2.score 6 | GROUP BY s1.id 7 | ORDER BY s1.score DESC; -------------------------------------------------------------------------------- /SQL/Rearrange Products Table.sql: -------------------------------------------------------------------------------- 1 | SELECT product_id, 2 | 'store1' AS store, 3 | store1 AS price 4 | FROM Products 5 | WHERE store1 IS NOT NULL 6 | 7 | UNION 8 | 9 | SELECT product_id, 10 | 'store2' AS store, 11 | store2 AS price 12 | FROM Products 13 | WHERE store2 IS NOT NULL 14 | 15 | UNION 16 | 17 | SELECT product_id, 18 | 'store3' AS store, 19 | store3 AS price 20 | FROM Products 21 | WHERE store3 IS NOT NULL 22 | 23 | ORDER BY product_id, store; 24 | -------------------------------------------------------------------------------- /SQL/Recyclable and Low Fat Products.sql: -------------------------------------------------------------------------------- 1 | SELECT product_id 2 | FROM Products 3 | WHERE low_fats = 'Y' 4 | AND recyclable = 'Y'; 5 | -------------------------------------------------------------------------------- /SQL/Rising Temperature.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT a.Id 2 | FROM Weather AS a, 3 | Weather AS b 4 | WHERE a.temperature > b.temperature 5 | AND DATEDIFF(a.recordDate, b.recordDate) = 1; 6 | -------------------------------------------------------------------------------- /SQL/Sales Analysis III.sql: -------------------------------------------------------------------------------- 1 | SELECT p.product_id, 2 | p.product_name 3 | FROM product AS p JOIN sales AS s 4 | ON p.product_id = s.product_id 5 | GROUP BY s.product_id 6 | HAVING MIN(s.sale_date) >= '2019-01-01' 7 | AND MAX(s.sale_date) <= '2019-03-31'; 8 | -------------------------------------------------------------------------------- /SQL/Sales Person.sql: -------------------------------------------------------------------------------- 1 | SELECT s.name 2 | FROM SalesPerson s 3 | WHERE s.sales_id NOT IN ( 4 | SELECT o.sales_id 5 | FROM Orders o LEFT JOIN Company c 6 | ON o.com_id = c.com_id 7 | WHERE c.name = 'RED' 8 | ); 9 | -------------------------------------------------------------------------------- /SQL/Second Highest Salary.sql: -------------------------------------------------------------------------------- 1 | SELECT ( 2 | SELECT DISTINCT Salary 3 | FROM Employee 4 | ORDER BY Salary DESC 5 | LIMIT 1 6 | OFFSET 1 7 | ) AS SecondHighestSalary; 8 | -------------------------------------------------------------------------------- /SQL/Swap Salary.sql: -------------------------------------------------------------------------------- 1 | UPDATE Salary 2 | SET sex = IF (sex = 'm', 'f', 'm'); 3 | -------------------------------------------------------------------------------- /SQL/The Latest Login in 2020.sql: -------------------------------------------------------------------------------- 1 | SELECT user_id, 2 | MAX(time_stamp) AS last_stamp 3 | FROM Logins 4 | WHERE YEAR(time_stamp) = 2020 5 | GROUP BY user_id; 6 | -------------------------------------------------------------------------------- /SQL/Top Travellers.sql: -------------------------------------------------------------------------------- 1 | SELECT name, 2 | COALESCE(SUM(distance), 0) AS travelled_distance 3 | FROM Users u LEFT JOIN Rides r 4 | ON u.id = r.user_id 5 | GROUP BY user_id 6 | ORDER BY 2 DESC, 1; 7 | -------------------------------------------------------------------------------- /SQL/Tree Node.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT a.id, 2 | CASE 3 | WHEN a.p_id IS NULL THEN 'Root' 4 | WHEN b.id IS NULL THEN 'Leaf' 5 | ELSE 'Inner' 6 | END AS Type 7 | FROM Tree a LEFT JOIN Tree b 8 | ON a.id = b.p_id 9 | ORDER BY a.id; 10 | -------------------------------------------------------------------------------- /SQL/User Activity for the Past 30 Days I.sql: -------------------------------------------------------------------------------- 1 | SELECT activity_date as day, 2 | COUNT(DISTINCT user_id) as active_users 3 | FROM Activity 4 | WHERE DATEDIFF('2019-07-27', activity_date) < 30 5 | AND activity_date <= '2019-07-27' 6 | GROUP BY activity_date; 7 | -------------------------------------------------------------------------------- /Shell/Tenth Line.sh: -------------------------------------------------------------------------------- 1 | sed -n 10p file.txt 2 | -------------------------------------------------------------------------------- /Shell/Transpose File.sh: -------------------------------------------------------------------------------- 1 | awk ' 2 | { 3 | for (i = 1; i <= NF; i++) { 4 | if (FNR == 1) { 5 | t[i] = $i; 6 | } else { 7 | t[i] = t[i] " " $i 8 | } 9 | } 10 | } 11 | END { 12 | for (i = 1; t[i] != ""; i++) { 13 | print t[i] 14 | } 15 | } 16 | ' file.txt 17 | -------------------------------------------------------------------------------- /Shell/Valid Phone Numbers.sh: -------------------------------------------------------------------------------- 1 | egrep "^(\([0-9]{3}\) |[0-9]{3}\-)[0-9]{3}\-[0-9]{4}$" file.txt 2 | -------------------------------------------------------------------------------- /Shell/Word Frequency.sh: -------------------------------------------------------------------------------- 1 | cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{ print $2, $1 }' 2 | -------------------------------------------------------------------------------- /infrastructure/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyrylo-Ktl/LeetCode-Solutions/31e0264f803cdc61da9da6fd3a83109a76d216d5/infrastructure/__init__.py -------------------------------------------------------------------------------- /infrastructure/requirements.txt: -------------------------------------------------------------------------------- 1 | pydantic==1.10.2 2 | requests==2.28.1 3 | SQLAlchemy==1.4.41 -------------------------------------------------------------------------------- /infrastructure/run.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | 4 | sys.path.append('.') 5 | from infrastructure.src.formatter import MarkdownFormatter 6 | 7 | if __name__ == '__main__': 8 | logging.basicConfig( 9 | level=logging.INFO, 10 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 11 | ) 12 | MarkdownFormatter.format() 13 | -------------------------------------------------------------------------------- /infrastructure/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyrylo-Ktl/LeetCode-Solutions/31e0264f803cdc61da9da6fd3a83109a76d216d5/infrastructure/src/__init__.py -------------------------------------------------------------------------------- /infrastructure/src/db/__init__.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import create_engine 2 | from sqlalchemy.orm import declarative_base, sessionmaker 3 | 4 | from infrastructure.config import PROBLEMS_DB_URL 5 | 6 | Base = declarative_base() 7 | 8 | 9 | class DatabaseSession: 10 | def __init__(self): 11 | self._engine = create_engine(url=PROBLEMS_DB_URL) 12 | self.session = sessionmaker(bind=self._engine) 13 | 14 | def create_all(self): 15 | Base.metadata.create_all(self._engine) 16 | 17 | 18 | db = DatabaseSession() 19 | -------------------------------------------------------------------------------- /infrastructure/src/db/schemas.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | from pydantic import BaseModel, Field 4 | 5 | from infrastructure.src.db.models import Problem 6 | 7 | 8 | class DifficultyEnum(str, Enum): 9 | easy = 'Easy' 10 | medium = 'Medium' 11 | hard = 'Hard' 12 | 13 | 14 | class ProblemSchema(BaseModel): 15 | id: int = Field(alias='questionFrontendId') 16 | title: str 17 | difficulty: DifficultyEnum 18 | is_premium: bool = Field(alias='isPaidOnly') 19 | 20 | @property 21 | def slug(self) -> str: 22 | return Problem.to_slug(self.title) 23 | 24 | class Config: 25 | use_enum_values = True 26 | -------------------------------------------------------------------------------- /infrastructure/src/resources/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyrylo-Ktl/LeetCode-Solutions/31e0264f803cdc61da9da6fd3a83109a76d216d5/infrastructure/src/resources/__init__.py -------------------------------------------------------------------------------- /infrastructure/src/resources/complexity_notations_table.txt: -------------------------------------------------------------------------------- 1 | | Notation | Name | Sign | Meaning | 2 | |:--------:|:------------:|:------:|:---------------------------:| 3 | | $o$ | Little O | $<$ | Less than | 4 | | $O$ | Big O | $\leq$ | Less than or equal to | 5 | | $\Theta$ | Theta | $=$ | Equal to | 6 | | $\Omega$ | Big Omega | $\geq$ | Greater than or equal to | 7 | | $\omega$ | Little Omega | $>$ | Greater than | -------------------------------------------------------------------------------- /infrastructure/src/resources/problems.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kyrylo-Ktl/LeetCode-Solutions/31e0264f803cdc61da9da6fd3a83109a76d216d5/infrastructure/src/resources/problems.db --------------------------------------------------------------------------------