├── .swift-format ├── 0001-0500 ├── 0001. Two Sum.swift ├── 0002. Add Two Numbers.swift ├── 0003. Longest Substring Without Repeating Characters.swift ├── 0004. Median of Two Sorted Arrays.swift ├── 0005. Longest Palindromic Substring.swift ├── 0006. ZigZag Conversion.swift ├── 0007. Reverse Integer.swift ├── 0008. String to Integer (atoi).swift ├── 0009. Palindrome Number.swift ├── 0010. Regular Expression Matching.swift ├── 0011. Container With Most Water.swift ├── 0012. Integer to Roman.swift ├── 0013. Roman to Integer.swift ├── 0014. Longest Common Prefix.swift ├── 0015. 3Sum.swift ├── 0016. 3Sum Closest.swift ├── 0017. Letter Combinations of a Phone Number.swift ├── 0018. 4Sum.swift ├── 0019. Remove Nth Node From End of List.swift ├── 0020. Valid Parentheses.swift ├── 0021. Merge Two Sorted Lists.swift ├── 0022. Generate Parentheses.swift ├── 0023. Merge k Sorted Lists.swift ├── 0024. Swap Nodes in Pairs.swift ├── 0025. Reverse Nodes in k-Group.swift ├── 0026. Remove Duplicates from Sorted Array.swift ├── 0027. Remove Element.swift ├── 0028. Implement strStr().swift ├── 0029. Divide Two Integers.swift ├── 0030. Substring with Concatenation of All Words.swift ├── 0031. Next Permutation.swift ├── 0032. Longest Valid Parentheses.swift ├── 0033. Search in Rotated Sorted Array.swift ├── 0034. Find First and Last Position of Element in Sorted Array.swift ├── 0035. Search Insert Position.swift ├── 0036. Valid Sudoku.swift ├── 0037. Sudoku Solver.swift ├── 0038. Count and Say.swift ├── 0039. Combination Sum.swift ├── 0040. Combination Sum II.swift ├── 0041. First Missing Positive.swift ├── 0042. Trapping Rain Water.swift ├── 0043. Multiply Strings.swift ├── 0044. Wildcard Matching.swift ├── 0045. Jump Game II.swift ├── 0046. Permutations.swift ├── 0047. Permutations II.swift ├── 0048. Rotate Image.swift ├── 0049. Group Anagrams.swift ├── 0050. Pow(x, n).swift ├── 0051. N-Queens.swift ├── 0052. N-Queens II.swift ├── 0053. Maximum Subarray.swift ├── 0054. Spiral Matrix.swift ├── 0055. Jump Game.swift ├── 0056. Merge Intervals.swift ├── 0057. Insert Interval.swift ├── 0058. Length of Last Word.swift ├── 0059. Spiral Matrix II.swift ├── 0060. Permutation Sequence.swift ├── 0061. Rotate List.swift ├── 0062. Unique Paths.swift ├── 0063. Unique Paths II.swift ├── 0064. Minimum Path Sum.swift ├── 0065. Valid Number.swift ├── 0066. Plus One.swift ├── 0067. Add Binary.swift ├── 0068. Text Justification.swift ├── 0069. Sqrt(x).swift ├── 0070. Climbing Stairs.swift ├── 0071. Simplify Path.swift ├── 0072. Edit Distance.swift ├── 0073. Set Matrix Zeroes.swift ├── 0074. Search a 2D Matrix.swift ├── 0075. Sort Colors.swift ├── 0076. Minimum Window Substring.swift ├── 0077. Combinations.swift ├── 0078. Subsets.swift ├── 0079. Word Search.swift ├── 0080. Remove Duplicates from Sorted Array II.swift ├── 0081. Search in Rotated Sorted Array II.swift ├── 0082. Remove Duplicates from Sorted List II.swift ├── 0083. Remove Duplicates from Sorted List.swift ├── 0084. Largest Rectangle in Histogram.swift ├── 0085. Maximal Rectangle.swift ├── 0086. Partition List.swift ├── 0087. Scramble String.swift ├── 0088. Merge Sorted Array.swift ├── 0089. Gray Code.swift ├── 0090. Subsets II.swift ├── 0091. Decode Ways.swift ├── 0092. Reverse Linked List II.swift ├── 0093. Restore IP Addresses.swift ├── 0094. Binary Tree Inorder Traversal.swift ├── 0095. Unique Binary Search Trees II.swift ├── 0096. Unique Binary Search Trees.swift ├── 0097. Interleaving String.swift ├── 0098. Validate Binary Search Tree.swift ├── 0099. Recover Binary Search Tree.swift ├── 0100. Same Tree.swift ├── 0101. Symmetric Tree.swift ├── 0102. Binary Tree Level Order Traversal.swift ├── 0103. Binary Tree Zigzag Level Order Traversal.swift ├── 0104. Maximum Depth of Binary Tree.swift ├── 0105. Construct Binary Tree from Preorder and Inorder Traversal.swift ├── 0106. Construct Binary Tree from Inorder and Postorder Traversal.swift ├── 0107. Binary Tree Level Order Traversal II.swift ├── 0108. Convert Sorted Array to Binary Search Tree.swift ├── 0109. Convert Sorted List to Binary Search Tree.swift ├── 0110. Balanced Binary Tree.swift ├── 0111. Minimum Depth of Binary Tree.swift ├── 0112. Path Sum.swift ├── 0113. Path Sum II.swift ├── 0114. Flatten Binary Tree to Linked List.swift ├── 0115. Distinct Subsequences.swift ├── 0116. Populating Next Right Pointers in Each Node.swift ├── 0117. Populating Next Right Pointers in Each Node II.swift ├── 0118. Pascal's Triangle.swift ├── 0119. Pascal's Triangle II.swift ├── 0120. Triangle.swift ├── 0121. Best Time to Buy and Sell Stock.swift ├── 0122. Best Time to Buy and Sell Stock II.swift ├── 0123. Best Time to Buy and Sell Stock III.swift ├── 0124. Binary Tree Maximum Path Sum.swift ├── 0125. Valid Palindrome.swift ├── 0126. Word Ladder II.swift ├── 0127. Word Ladder.swift ├── 0128. Longest Consecutive Sequence.swift ├── 0129. Sum Root to Leaf Numbers.swift ├── 0130. Surrounded Regions.swift ├── 0131. Palindrome Partitioning.swift ├── 0132. Palindrome Partitioning II.swift ├── 0133. Clone Graph.swift ├── 0134. Gas Station.swift ├── 0135. Candy.swift ├── 0136. Single Number.swift ├── 0137. Single Number II.swift ├── 0138. Copy List with Random Pointer.swift ├── 0139. Word Break.swift ├── 0140. Word Break II.swift ├── 0141. Linked List Cycle.swift ├── 0142. Linked List Cycle II.swift ├── 0143. Reorder List.swift ├── 0144. Binary Tree Preorder Traversal.swift ├── 0145. Binary Tree Postorder Traversal.swift ├── 0146. LRU Cache.swift ├── 0147. Insertion Sort List.swift ├── 0148. Sort List.swift ├── 0149. Max Points on a Line.swift ├── 0150. Evaluate Reverse Polish Notation.swift ├── 0151. Reverse Words in a String.swift ├── 0152. Maximum Product Subarray.swift ├── 0153. Find Minimum in Rotated Sorted Array.swift ├── 0154. Find Minimum in Rotated Sorted Array II.swift ├── 0155. Min Stack.swift ├── 0160. Intersection of Two Linked Lists.swift ├── 0162. Find Peak Element.swift ├── 0164. Maximum Gap.swift ├── 0165. Compare Version Numbers.swift ├── 0166. Fraction to Recurring Decimal.swift ├── 0167. Two Sum II - Input array is sorted.swift ├── 0168. Excel Sheet Column Title.swift ├── 0169. Majority Element.swift ├── 0171. Excel Sheet Column Number.swift ├── 0172. Factorial Trailing Zeroes.swift ├── 0173. Binary Search Tree Iterator.swift ├── 0174. Dungeon Game.swift ├── 0175. Combine Two Tables.sql ├── 0176. Second Highest Salary.sql ├── 0177. Nth Highest Salary.sql ├── 0178. Rank Scores.sql ├── 0179. Largest Number.swift ├── 0180. Consecutive Numbers.sql ├── 0181. Employees Earning More Than Their Managers.sql ├── 0182. Duplicate Emails.sql ├── 0183. Customers Who Never Order.sql ├── 0184. Department Highest Salary.sql ├── 0185. Department Top Three Salaries.sql ├── 0187. Repeated DNA Sequences.swift ├── 0188. Best Time to Buy and Sell Stock IV.swift ├── 0189. Rotate Array.swift ├── 0190. Reverse Bits.swift ├── 0191. Number of 1 Bits.swift ├── 0192. Word Frequency.sh ├── 0193. Valid Phone Numbers.sh ├── 0194. Transpose File.sh ├── 0195. Tenth Line.sh ├── 0196. Delete Duplicate Emails.sql ├── 0197. Rising Temperature.sql ├── 0198. House Robber.swift ├── 0199. Binary Tree Right Side View.swift ├── 0200. Number of Islands.swift ├── 0201. Bitwise AND of Numbers Range.swift ├── 0202. Happy Number.swift ├── 0203. Remove Linked List Elements.swift ├── 0204. Count Primes.swift ├── 0205. Isomorphic Strings.swift ├── 0206. Reverse Linked List.swift ├── 0207. Course Schedule.swift ├── 0208. Implement Trie (Prefix Tree).swift ├── 0209. Minimum Size Subarray Sum.swift ├── 0210. Course Schedule II.swift ├── 0211. Design Add and Search Words Data Structure.swift ├── 0212. Word Search II.swift ├── 0213. House Robber II.swift ├── 0214. Shortest Palindrome.swift ├── 0215. Kth Largest Element in an Array.swift ├── 0216. Combination Sum III.swift ├── 0217. Contains Duplicate.swift ├── 0218. The Skyline Problem.swift ├── 0219. Contains Duplicate II.swift ├── 0220. Contains Duplicate III.swift ├── 0221. Maximal Square.swift ├── 0222. Count Complete Tree Nodes.swift ├── 0223. Rectangle Area.swift ├── 0224. Basic Calculator.swift ├── 0225. Implement Stack using Queues.swift ├── 0226. Invert Binary Tree.swift ├── 0227. Basic Calculator II.swift ├── 0228. Summary Ranges.swift ├── 0229. Majority Element II.swift ├── 0230. Kth Smallest Element in a BST.swift ├── 0231. Power of Two.swift ├── 0232. Implement Queue using Stacks.swift ├── 0233. Number of Digit One.swift ├── 0234. Palindrome Linked List.swift ├── 0235. Lowest Common Ancestor of a Binary Search Tree.swift ├── 0236. Lowest Common Ancestor of a Binary Tree.swift ├── 0237. Delete Node in a Linked List.swift ├── 0238. Product of Array Except Self.swift ├── 0239. Sliding Window Maximum.swift ├── 0240. Search a 2D Matrix II.swift ├── 0241. Different Ways to Add Parentheses.swift ├── 0242. Valid Anagram.swift ├── 0257. Binary Tree Paths.swift ├── 0258. Add Digits.swift ├── 0260. Single Number III.swift ├── 0262. Trips and Users.sql ├── 0263. Ugly Number.swift ├── 0264. Ugly Number II.swift ├── 0268. Missing Number.swift ├── 0273. Integer to English Words.swift ├── 0274. H-Index.swift ├── 0275. H-Index II.swift ├── 0278. First Bad Version.swift ├── 0279. Perfect Squares.swift ├── 0282. Expression Add Operators.swift ├── 0283. Move Zeroes.swift ├── 0284. Peeking Iterator.swift ├── 0287. Find the Duplicate Number.swift ├── 0289. Game of Life.swift ├── 0290. Word Pattern.swift ├── 0292. Nim Game.swift ├── 0295. Find Median from Data Stream.swift ├── 0297. Serialize and Deserialize Binary Tree.swift ├── 0299. Bulls and Cows.swift ├── 0300. Longest Increasing Subsequence.swift ├── 0301. Remove Invalid Parentheses.swift ├── 0303. Range Sum Query - Immutable.swift ├── 0304. Range Sum Query 2D - Immutable.swift ├── 0306. Additive Number.swift ├── 0307. Range Sum Query - Mutable.swift ├── 0309. Best Time to Buy and Sell Stock with Cooldown.swift ├── 0310. Minimum Height Trees.swift ├── 0312. Burst Balloons.swift ├── 0313. Super Ugly Number.swift ├── 0315. Count of Smaller Numbers After Self.swift ├── 0318. Maximum Product of Word Lengths.swift ├── 0319. Bulb Switcher.swift ├── 0321. Create Maximum Number.swift ├── 0322. Coin Change.swift ├── 0324. Wiggle Sort II.swift ├── 0326. Power of Three.swift ├── 0327. Count of Range Sum.swift ├── 0328. Odd Even Linked List.swift ├── 0329. Longest Increasing Path in a Matrix.swift ├── 0330. Patching Array.swift ├── 0331. Verify Preorder Serialization of a Binary Tree.swift ├── 0332. Reconstruct Itinerary.swift ├── 0334. Increasing Triplet Subsequence.swift ├── 0335. Self Crossing.swift ├── 0336. Palindrome Pairs.swift ├── 0337. House Robber III.swift ├── 0338. Counting Bits.swift ├── 0341. Flatten Nested List Iterator.swift ├── 0342. Power of Four.swift ├── 0343. Integer Break.swift ├── 0344. Reverse String.swift ├── 0345. Reverse Vowels of a String.swift ├── 0347. Top K Frequent Elements.swift ├── 0349. Intersection of Two Arrays.swift ├── 0350. Intersection of Two Arrays II.swift ├── 0352. Data Stream as Disjoint Intervals.swift ├── 0354. Russian Doll Envelopes.swift ├── 0355. Design Twitter.swift ├── 0357. Count Numbers with Unique Digits.swift ├── 0363. Max Sum of Rectangle No Larger Than K.swift ├── 0365. Water and Jug Problem.swift ├── 0367. Valid Perfect Square.swift ├── 0368. Largest Divisible Subset.swift ├── 0371. Sum of Two Integers.swift ├── 0372. Super Pow.swift ├── 0373. Find K Pairs with Smallest Sums.swift ├── 0374. Guess Number Higher or Lower.swift ├── 0375. Guess Number Higher or Lower II.swift ├── 0376. Wiggle Subsequence.swift ├── 0377. Combination Sum IV.swift ├── 0378. Kth Smallest Element in a Sorted Matrix.swift ├── 0380. Insert Delete GetRandom O(1).swift ├── 0381. Insert Delete GetRandom O(1) - Duplicates allowed.swift ├── 0382. Linked List Random Node.swift ├── 0383. Ransom Note.swift ├── 0384. Shuffle an Array.swift ├── 0385. Mini Parser.swift ├── 0386. Lexicographical Numbers.swift ├── 0387. First Unique Character in a String.swift ├── 0388. Longest Absolute File Path.swift ├── 0389. Find the Difference.swift ├── 0390. Elimination Game.swift ├── 0391. Perfect Rectangle.swift ├── 0392. Is Subsequence.swift ├── 0393. UTF-8 Validation.swift ├── 0394. Decode String.swift ├── 0395. Longest Substring with At Least K Repeating Characters.swift ├── 0396. Rotate Function.swift ├── 0397. Integer Replacement.swift ├── 0399. Evaluate Division.swift ├── 0400. Nth Digit.swift ├── 0401. Binary Watch.swift ├── 0402. Remove K Digits.swift ├── 0403. Frog Jump.swift ├── 0404. Sum of Left Leaves.swift ├── 0405. Convert a Number to Hexadecimal.swift ├── 0406. Queue Reconstruction by Height.swift ├── 0407. Trapping Rain Water II.swift ├── 0409. Longest Palindrome.swift ├── 0410. Split Array Largest Sum.swift ├── 0412. Fizz Buzz.swift ├── 0413. Arithmetic Slices.swift ├── 0414. Third Maximum Number.swift ├── 0415. Add Strings.swift ├── 0416. Partition Equal Subset Sum.swift ├── 0417. Pacific Atlantic Water Flow.swift ├── 0419. Battleships in a Board.swift ├── 0420. Strong Password Checker.swift ├── 0421. Maximum XOR of Two Numbers in an Array.swift ├── 0423. Reconstruct Original Digits from English.swift ├── 0424. Longest Repeating Character Replacement.swift ├── 0427. Construct Quad Tree.swift ├── 0429. N-ary Tree Level Order Traversal.swift ├── 0430. Flatten a Multilevel Doubly Linked List.swift ├── 0432. All Oone Data Structure.swift ├── 0433. Minimum Genetic Mutation.swift ├── 0434. Number of Segments in a String.swift ├── 0435. Non-overlapping Intervals.swift ├── 0436. Find Right Interval.swift ├── 0437. Path Sum III.swift ├── 0438. Find All Anagrams in a String.swift ├── 0440. K-th Smallest in Lexicographical Order.swift ├── 0441. Arranging Coins.swift ├── 0442. Find All Duplicates in an Array.swift ├── 0445. Add Two Numbers II.swift ├── 0446. Arithmetic Slices II - Subsequence.swift ├── 0447. Number of Boomerangs.swift ├── 0448. Find All Numbers Disappeared in an Array.swift ├── 0449. Serialize and Deserialize BST.swift ├── 0450. Delete Node in a BST.swift ├── 0451. Sort Characters By Frequency.swift ├── 0452. Minimum Number of Arrows to Burst Balloons.swift ├── 0453. Minimum Moves to Equal Array Elements.swift ├── 0454. 4Sum II.swift ├── 0455. Assign Cookies.swift ├── 0456. 132 Pattern.swift ├── 0457. Circular Array Loop.swift ├── 0458. Poor Pigs.swift ├── 0459. Repeated Substring Pattern.swift ├── 0460. LFU Cache.swift ├── 0461. Hamming Distance.swift ├── 0462. Minimum Moves to Equal Array Elements II.swift ├── 0463. Island Perimeter.swift ├── 0464. Can I Win.swift ├── 0466. Count The Repetitions.swift ├── 0467. Unique Substrings in Wraparound String.swift ├── 0468. Validate IP Address.swift ├── 0470. Implement Rand10() Using Rand7().swift ├── 0472. Concatenated Words.swift ├── 0473. Matchsticks to Square.swift ├── 0474. Ones and Zeroes.swift ├── 0475. Heaters.swift ├── 0476. Number Complement.swift ├── 0477. Total Hamming Distance.swift ├── 0478. Generate Random Point in a Circle.swift ├── 0479. Largest Palindrome Product.swift ├── 0480. Sliding Window Median.swift ├── 0481. Magical String.swift ├── 0482. License Key Formatting.swift ├── 0483. Smallest Good Base.swift ├── 0485. Max Consecutive Ones.swift ├── 0486. Predict the Winner.swift ├── 0491. Increasing Subsequences.swift ├── 0492. Construct the Rectangle.swift ├── 0493. Reverse Pairs.swift ├── 0494. Target Sum.swift ├── 0495. Teemo Attacking.swift ├── 0496. Next Greater Element I.swift ├── 0497. Random Point in Non-overlapping Rectangles.swift ├── 0498. Diagonal Traverse.swift └── 0500. Keyboard Row.swift ├── 0501-1000 ├── 0501. Find Mode in Binary Search Tree.swift ├── 0503. Next Greater Element II.swift ├── 0504. Base 7.swift ├── 0506. Relative Ranks.swift ├── 0507. Perfect Number.swift ├── 0508. Most Frequent Subtree Sum.swift ├── 0509. Fibonacci Number.swift ├── 0513. Find Bottom Left Tree Value.swift ├── 0514. Freedom Trail.swift ├── 0515. Find Largest Value in Each Tree Row.swift ├── 0516. Longest Palindromic Subsequence.swift ├── 0517. Super Washing Machines.swift ├── 0518. Coin Change 2.swift ├── 0520. Detect Capital.swift ├── 0521. Longest Uncommon Subsequence I.swift ├── 0522. Longest Uncommon Subsequence II.swift ├── 0523. Continuous Subarray Sum.swift ├── 0524. Longest Word in Dictionary through Deleting.swift ├── 0525. Contiguous Array.swift ├── 0526. Beautiful Arrangement.swift ├── 0528. Random Pick with Weight.swift ├── 0529. Minesweeper.swift ├── 0530. Minimum Absolute Difference in BST.swift ├── 0532. K-diff Pairs in an Array.swift ├── 0535. Encode and Decode TinyURL.swift ├── 0537. Complex Number Multiplication.swift ├── 0538. Convert BST to Greater Tree.swift ├── 0539. Minimum Time Difference.swift ├── 0540. Single Element in a Sorted Array.swift ├── 0541. Reverse String II.swift ├── 0542. 01 Matrix.swift ├── 0543. Diameter of Binary Tree.swift ├── 0546. Remove Boxes.swift ├── 0547. Number of Provinces.swift ├── 0550. Game Play Analysis IV.sql ├── 0551. Student Attendance Record I.swift ├── 0552. Student Attendance Record II.swift ├── 0553. Optimal Division.swift ├── 0554. Brick Wall.swift ├── 0556. Next Greater Element III.swift ├── 0557. Reverse Words in a String III.swift ├── 0559. Maximum Depth of N-ary Tree.swift ├── 0560. Subarray Sum Equals K.swift ├── 0561. Array Partition I.swift ├── 0563. Binary Tree Tilt.swift ├── 0564. Find the Closest Palindrome.swift ├── 0565. Array Nesting.swift ├── 0566. Reshape the Matrix.swift ├── 0567. Permutation in String.swift ├── 0570. Managers with at Least 5 Direct Reports.sql ├── 0572. Subtree of Another Tree.swift ├── 0575. Distribute Candies.swift ├── 0576. Out of Boundary Paths.swift ├── 0577. Employee Bonus.sql ├── 0581. Shortest Unsorted Continuous Subarray.swift ├── 0583. Delete Operation for Two Strings.swift ├── 0585. Investments in 2016.sql ├── 0589. N-ary Tree Preorder Traversal.swift ├── 0590. N-ary Tree Postorder Traversal.swift ├── 0592. Fraction Addition and Subtraction.swift ├── 0593. Valid Square.swift ├── 0594. Longest Harmonious Subsequence.swift ├── 0595. Big Countries.sql ├── 0596. Classes More Than 5 Students.sql ├── 0598. Range Addition II.swift ├── 0599. Minimum Index Sum of Two Lists.swift ├── 0600. Non-negative Integers without Consecutive Ones.swift ├── 0601. Human Traffic of Stadium.sql ├── 0602. Friend Requests II Who Has the Most Friends.sql ├── 0605. Can Place Flowers.swift ├── 0606. Construct String from Binary Tree.swift ├── 0609. Find Duplicate File in System.swift ├── 0610. Triangle Judgement.sql ├── 0611. Valid Triangle Number.swift ├── 0617. Merge Two Binary Trees.swift ├── 0619. Biggest Single Number.sql ├── 0620. Not Boring Movies.sql ├── 0621. Task Scheduler.swift ├── 0622. Design Circular Queue.swift ├── 0623. Add One Row to Tree.swift ├── 0626. Exchange Seats.sql ├── 0627. Swap Salary.sql ├── 0628. Maximum Product of Three Numbers.swift ├── 0629. K Inverse Pairs Array.swift ├── 0630. Course Schedule III.swift ├── 0632. Smallest Range Covering Elements from K Lists.swift ├── 0633. Sum of Square Numbers.swift ├── 0636. Exclusive Time of Functions.swift ├── 0637. Average of Levels in Binary Tree.swift ├── 0638. Shopping Offers.swift ├── 0639. Decode Ways II.swift ├── 0640. Solve the Equation.swift ├── 0641. Design Circular Deque.swift ├── 0643. Maximum Average Subarray I.swift ├── 0645. Set Mismatch.swift ├── 0646. Maximum Length of Pair Chain.swift ├── 0647. Palindromic Substrings.swift ├── 0648. Replace Words.swift ├── 0649. Dota2 Senate.swift ├── 0650. 2 Keys Keyboard.swift ├── 0652. Find Duplicate Subtrees.swift ├── 0653. Two Sum IV - Input is a BST.swift ├── 0654. Maximum Binary Tree.swift ├── 0655. Print Binary Tree.swift ├── 0657. Robot Return to Origin.swift ├── 0658. Find K Closest Elements.swift ├── 0659. Split Array into Consecutive Subsequences.swift ├── 0661. Image Smoother.swift ├── 0662. Maximum Width of Binary Tree.swift ├── 0664. Strange Printer.swift ├── 0665. Non-decreasing Array.swift ├── 0667. Beautiful Arrangement II.swift ├── 0668. Kth Smallest Number in Multiplication Table.swift ├── 0669. Trim a Binary Search Tree.swift ├── 0670. Maximum Swap.swift ├── 0671. Second Minimum Node In a Binary Tree.swift ├── 0672. Bulb Switcher II.swift ├── 0673. Number of Longest Increasing Subsequence.swift ├── 0674. Longest Continuous Increasing Subsequence.swift ├── 0676. Implement Magic Dictionary.swift ├── 0677. Map Sum Pairs.swift ├── 0678. Valid Parenthesis String.swift ├── 0679. 24 Game.swift ├── 0680. Valid Palindrome II.swift ├── 0682. Baseball Game.swift ├── 0684. Redundant Connection.swift ├── 0685. Redundant Connection II.swift ├── 0686. Repeated String Match.swift ├── 0687. Longest Univalue Path.swift ├── 0688. Knight Probability in Chessboard.swift ├── 0689. Maximum Sum of 3 Non-Overlapping Subarrays.swift ├── 0690. Employee Importance.swift ├── 0691. Stickers to Spell Word.swift ├── 0692. Top K Frequent Words.swift ├── 0693. Binary Number with Alternating Bits.swift ├── 0695. Max Area of Island.swift ├── 0696. Count Binary Substrings.swift ├── 0697. Degree of an Array.swift ├── 0698. Partition to K Equal Sum Subsets.swift ├── 0699. Falling Squares.swift ├── 0700. Search in a Binary Search Tree.swift ├── 0701. Insert into a Binary Search Tree.swift ├── 0703. Kth Largest Element in a Stream.swift ├── 0704. Binary Search.swift ├── 0705. Design HashSet.swift ├── 0706. Design HashMap.swift ├── 0707. Design Linked List.swift ├── 0709. To Lower Case.swift ├── 0710. Random Pick with Blacklist.swift ├── 0712. Minimum ASCII Delete Sum for Two Strings.swift ├── 0713. Subarray Product Less Than K.swift ├── 0714. Best Time to Buy and Sell Stock with Transaction Fee.swift ├── 0715. Range Module.swift ├── 0717. 1-bit and 2-bit Characters.swift ├── 0718. Maximum Length of Repeated Subarray.swift ├── 0719. Find K-th Smallest Pair Distance.swift ├── 0720. Longest Word in Dictionary.swift ├── 0721. Accounts Merge.swift ├── 0722. Remove Comments.swift ├── 0724. Find Pivot Index.swift ├── 0725. Split Linked List in Parts.swift ├── 0726. Number of Atoms.swift ├── 0728. Self Dividing Numbers.swift ├── 0729. My Calendar I.swift ├── 0730. Count Different Palindromic Subsequences.swift ├── 0731. My Calendar II.swift ├── 0733. Flood Fill.swift ├── 0735. Asteroid Collision.swift ├── 0738. Monotone Increasing Digits.swift ├── 0739. Daily Temperatures.swift ├── 0740. Delete and Earn.swift ├── 0741. Cherry Pickup.swift ├── 0743. Network Delay Time.swift ├── 0744. Find Smallest Letter Greater Than Target.swift ├── 0745. Prefix and Suffix Search.swift ├── 0746. Min Cost Climbing Stairs.swift ├── 0747. Largest Number At Least Twice of Others.swift ├── 0748. Shortest Completing Word.swift ├── 0749. Contain Virus.swift ├── 0752. Open the Lock.swift ├── 0753. Cracking the Safe.swift ├── 0754. Reach a Number.swift ├── 0756. Pyramid Transition Matrix.swift ├── 0762. Prime Number of Set Bits in Binary Representation.swift ├── 0763. Partition Labels.swift ├── 0764. Largest Plus Sign.swift ├── 0765. Couples Holding Hands.swift ├── 0766. Toeplitz Matrix.swift ├── 0767. Reorganize String.swift ├── 0768. Max Chunks To Make Sorted II.swift ├── 0769. Max Chunks To Make Sorted.swift ├── 0771. Jewels and Stones.swift ├── 0773. Sliding Puzzle.swift ├── 0777. Swap Adjacent in LR String.swift ├── 0778. Swim in Rising Water.swift ├── 0779. K-th Symbol in Grammar.swift ├── 0780. Reaching Points.swift ├── 0781. Rabbits in Forest.swift ├── 0783. Minimum Distance Between BST Nodes.swift ├── 0784. Letter Case Permutation.swift ├── 0785. Is Graph Bipartite.swift ├── 0786. K-th Smallest Prime Fraction.swift ├── 0787. Cheapest Flights Within K Stops.swift ├── 0788. Rotated Digits.swift ├── 0789. Escape The Ghosts.swift ├── 0790. Domino and Tromino Tiling.swift ├── 0791. Custom Sort String.swift ├── 0792. Number of Matching Subsequences.swift ├── 0793. Preimage Size of Factorial Zeroes Function.swift ├── 0794. Valid Tic-Tac-Toe State.swift ├── 0795. Number of Subarrays with Bounded Maximum.swift ├── 0796. Rotate String.swift ├── 0797. All Paths From Source to Target.swift ├── 0799. Champagne Tower.swift ├── 0801. Minimum Swaps To Make Sequences Increasing.swift ├── 0802. Find Eventual Safe States.swift ├── 0803. Bricks Falling When Hit.swift ├── 0804. Unique Morse Code Words.swift ├── 0805. Split Array With Same Average.swift ├── 0806. Number of Lines To Write String.swift ├── 0807. Max Increase to Keep City Skyline.swift ├── 0808. Soup Servings.swift ├── 0809. Expressive Words.swift ├── 0810. Chalkboard XOR Game.swift ├── 0811. Subdomain Visit Count.swift ├── 0812. Largest Triangle Area.swift ├── 0813. Largest Sum of Averages.swift ├── 0814. Binary Tree Pruning.swift ├── 0815. Bus Routes.swift ├── 0816. Ambiguous Coordinates.swift ├── 0817. Linked List Componentsa.swift ├── 0818. Race Car.swift ├── 0819. Most Common Word.swift ├── 0820. Short Encoding of Words.swift ├── 0821. Shortest Distance to a Character.swift ├── 0822. Card Flipping Game.swift ├── 0823. Binary Trees With Factors.swift ├── 0824. Goat Latin.swift ├── 0825. Friends Of Appropriate Ages.swift ├── 0826. Most Profit Assigning Work.swift ├── 0827. Making A Large Island.swift ├── 0828. Count Unique Characters of All Substrings of a Given String.swift ├── 0829. Consecutive Numbers Sum.swift ├── 0830. Positions of Large Groups.swift ├── 0831. Masking Personal Information.swift ├── 0832. Flipping an Image.swift ├── 0833. Find And Replace in String.swift ├── 0834. Sum of Distances in Tree.swift ├── 0835. Image Overlap.swift ├── 0836. Rectangle Overlap.swift ├── 0837. New 21 Game.swift ├── 0838. Push Dominoes.swift ├── 0839. Similar String Groups.swift ├── 0840. Magic Squares In Grid.swift ├── 0841. Keys and Rooms.swift ├── 0842. Split Array into Fibonacci Sequence.swift ├── 0843. Guess the Word.swift ├── 0844. Backspace String Compare.swift ├── 0845. Longest Mountain in Array.swift ├── 0846. Hand of Straights.swift ├── 0847. Shortest Path Visiting All Nodes.swift ├── 0848. Shifting Letters.swift ├── 0849. Maximize Distance to Closest Person.swift ├── 0850. Rectangle Area II.swift ├── 0851. Loud and Rich.swift ├── 0852. Peak Index in a Mountain Array.swift ├── 0853. Car Fleet.swift ├── 0854. K-Similar Strings.swift ├── 0856. Score of Parentheses.swift ├── 0857. Minimum Cost to Hire K Workers.swift ├── 0858. Mirror Reflection.swift ├── 0859. Buddy Strings.swift ├── 0860. Lemonade Change.swift ├── 0861. Score After Flipping Matrix.swift ├── 0862. Shortest Subarray with Sum at Least K.swift ├── 0863. All Nodes Distance K in Binary Tree.swift ├── 0864. Shortest Path to Get All Keys.swift ├── 0865. Smallest Subtree with all the Deepest Nodes.swift ├── 0866. Prime Palindrome.swift ├── 0867. Transpose Matrix.swift ├── 0868. Binary Gap.swift ├── 0869. Reordered Power of 2.swift ├── 0870. Advantage Shuffle.swift ├── 0871. Minimum Number of Refueling Stops.swift ├── 0872. Leaf-Similar Trees.swift ├── 0873. Length of Longest Fibonacci Subsequence.swift ├── 0874. Walking Robot Simulation.swift ├── 0875. Koko Eating Bananas.swift ├── 0876. Middle of the Linked List.swift ├── 0877. Stone Game.swift ├── 0878. Nth Magical Number.swift ├── 0879. Profitable Schemes.swift ├── 0880. Decoded String at Index.swift ├── 0881. Boats to Save People.swift ├── 0883. Projection Area of 3D Shapes.swift ├── 0884. Uncommon Words from Two Sentences.swift ├── 0885. Spiral Matrix III.swift ├── 0886. Possible Bipartition.swift ├── 0887. Super Egg Drop.swift ├── 0888. Fair Candy Swap.swift ├── 0889. Construct Binary Tree from Preorder and Postorder Traversal.swift ├── 0890. Find and Replace Pattern.swift ├── 0891. Sum of Subsequence Widths.swift ├── 0892. Surface Area of 3D Shapes.swift ├── 0893. Groups of Special-Equivalent Strings.swift ├── 0894. All Possible Full Binary Trees.swift ├── 0895. Maximum Frequency Stack.swift ├── 0896. Monotonic Array.swift ├── 0897. Increasing Order Search Tree.swift ├── 0898. Bitwise ORs of Subarrays.swift ├── 0899. Orderly Queue.swift ├── 0900. RLE Iterator.swift ├── 0901. Online Stock Span.swift ├── 0902. Numbers At Most N Given Digit Set.swift ├── 0903. Valid Permutations for DI Sequence.swift ├── 0904. Fruit Into Baskets.swift ├── 0905. Sort Array By Parity.swift ├── 0906. Super Palindromes.swift ├── 0907. Sum of Subarray Minimums.swift ├── 0908. Smallest Range I.swift ├── 0909. Snakes and Ladders.swift ├── 0910. Smallest Range II.swift ├── 0911. Online Election.swift ├── 0912. Sort an Array.swift ├── 0913. Cat and Mouse.swift ├── 0914. X of a Kind in a Deck of Cards.swift ├── 0915. Partition Array into Disjoint Intervals.swift ├── 0916. Word Subsets.swift ├── 0917. Reverse Only Letters.swift ├── 0918. Maximum Sum Circular Subarray.swift ├── 0919. Complete Binary Tree Inserter.swift ├── 0920. Number of Music Playlists.swift ├── 0921. Minimum Add to Make Parentheses Valid.swift ├── 0922. Sort Array By Parity II.swift ├── 0923. 3Sum With Multiplicity.swift ├── 0924. Minimize Malware Spread.swift ├── 0925. Long Pressed Name.swift ├── 0926. Flip String to Monotone Increasing.swift ├── 0928. Minimize Malware Spread II.swift ├── 0929. Unique Email Addresses.swift ├── 0930. Binary Subarrays With Sum.swift ├── 0931. Minimum Falling Path Sum.swift ├── 0932. Beautiful Array.swift ├── 0933. Number of Recent Calls.swift ├── 0934. Shortest Bridge.swift ├── 0935. Knight Dialer.swift ├── 0936. Stamping The Sequence.swift ├── 0937. Reorder Data in Log Files.swift ├── 0938. Range Sum of BST.swift ├── 0939. Minimum Area Rectangle.swift ├── 0940. Distinct Subsequences II.swift ├── 0941. Valid Mountain Array.swift ├── 0942. DI String Match.swift ├── 0943. Find the Shortest Superstring.swift ├── 0944. Delete Columns to Make Sorted.swift ├── 0945. Minimum Increment to Make Array Unique.swift ├── 0946. Validate Stack Sequences.swift ├── 0947. Most Stones Removed with Same Row or Column.swift ├── 0948. Bag of Tokens.swift ├── 0949. Largest Time for Given Digits.swift ├── 0950. Reveal Cards In Increasing Order.swift ├── 0951. Flip Equivalent Binary Trees.swift ├── 0952. Largest Component Size by Common Factor.swift ├── 0953. Verifying an Alien Dictionary.swift ├── 0955. Delete Columns to Make Sorted II.swift ├── 0956. Tallest Billboard.swift ├── 0957. Prison Cells After N Days.swift ├── 0958. Check Completeness of a Binary Tree.swift ├── 0959. Regions Cut By Slashes.swift ├── 0960. Delete Columns to Make Sorted III.swift ├── 0961. N-Repeated Element in Size 2N Array.swift ├── 0962. Maximum Width Ramp.swift ├── 0963. Minimum Area Rectangle II.swift ├── 0964. Least Operators to Express Number.swift ├── 0965. Univalued Binary Tree.swift ├── 0966. Vowel Spellchecker.swift ├── 0967. Numbers With Same Consecutive Differences.swift ├── 0968. Binary Tree Cameras.swift ├── 0969. Pancake Sorting.swift ├── 0970. Powerful Integers.swift ├── 0971. Flip Binary Tree To Match Preorder Traversal.swift ├── 0972. Equal Rational Numbers.swift ├── 0973. K Closest Points to Origin.swift ├── 0974. Subarray Sums Divisible by K.swift ├── 0976. Largest Perimeter Triangle.swift ├── 0977. Squares of a Sorted Array.swift ├── 0978. Longest Turbulent Subarray.swift ├── 0979. Distribute Coins in Binary Tree.swift ├── 0980. Unique Paths III.swift ├── 0981. Time Based Key-Value Store.swift ├── 0982. Triples with Bitwise AND Equal To Zero.swift ├── 0983. Minimum Cost For Tickets.swift ├── 0984. String Without AAA or BBB.swift ├── 0985. Sum of Even Numbers After Queries.swift ├── 0986. Interval List Intersections.swift ├── 0987. Vertical Order Traversal of a Binary Tree.swift ├── 0988. Smallest String Starting From Leaf.swift ├── 0989. Add to Array-Form of Integer.swift ├── 0990. Satisfiability of Equality Equations.swift ├── 0991. Broken Calculator.swift ├── 0992. Subarrays with K Different Integers.swift ├── 0993. Cousins in Binary Tree.swift ├── 0994. Rotting Oranges.swift ├── 0995. Minimum Number of K Consecutive Bit Flips.swift ├── 0996. Number of Squareful Arrays.swift ├── 0997. Find the Town Judge.swift ├── 0998. Maximum Binary Tree II.swift └── 0999. Available Captures for Rook.swift ├── 1001-1500 ├── 1001. Grid Illumination.swift ├── 1002. Find Common Characters.swift ├── 1003. Check If Word Is Valid After Substitutions.swift ├── 1004. Max Consecutive Ones III.swift ├── 1005. Maximize Sum Of Array After K Negations.swift ├── 1006. Clumsy Factorial.swift ├── 1007. Minimum Domino Rotations For Equal Row.swift ├── 1008. Construct Binary Search Tree from Preorder Traversal.swift ├── 1009. Complement of Base 10 Integer.swift ├── 1010. Pairs of Songs With Total Durations Divisible by 60.swift ├── 1011. Capacity To Ship Packages Within D Days.swift ├── 1012. Numbers With Repeated Digits.swift ├── 1013. Partition Array Into Three Parts With Equal Sum.swift ├── 1014. Best Sightseeing Pair.swift ├── 1015. Smallest Integer Divisible by K.swift ├── 1016. Binary String With Substrings Representing 1 To N.swift ├── 1017. Convert to Base -2.swift ├── 1018. Binary Prefix Divisible By 5.swift ├── 1019. Next Greater Node In Linked List.swift ├── 1020. Number of Enclaves.swift ├── 1021. Remove Outermost Parentheses.swift ├── 1022. Sum of Root To Leaf Binary Numbers.swift ├── 1023. Camelcase Matching.swift ├── 1024. Video Stitching.swift ├── 1025. Divisor Game.swift ├── 1026. Maximum Difference Between Node and Ancestor.swift ├── 1027. Longest Arithmetic Subsequence.swift ├── 1028. Recover a Tree From Preorder Traversal.swift ├── 1029. Two City Scheduling.swift ├── 1030. Matrix Cells in Distance Order.swift ├── 1031. Maximum Sum of Two Non-Overlapping Subarrays.swift ├── 1032. Stream of Characters.swift ├── 1033. Moving Stones Until Consecutive.swift ├── 1034. Coloring A Border.swift ├── 1035. Uncrossed Lines.swift ├── 1036. Escape a Large Maze.swift ├── 1037. Valid Boomerang.swift ├── 1038. Binary Search Tree to Greater Sum Tree.swift ├── 1039. Minimum Score Triangulation of Polygon.swift ├── 1040. Moving Stones Until Consecutive II.swift ├── 1041. Robot Bounded In Circle.swift ├── 1042. Flower Planting With No Adjacent.swift ├── 1043. Partition Array for Maximum Sum.swift ├── 1044. Longest Duplicate Substring.swift ├── 1045. Customers Who Bought All Products.sql ├── 1046. Last Stone Weight.swift ├── 1047. Remove All Adjacent Duplicates In String.swift ├── 1048. Longest String Chain.swift ├── 1049. Last Stone Weight II.swift ├── 1051. Height Checker.swift ├── 1052. Grumpy Bookstore Owner.swift ├── 1053. Previous Permutation With One Swap.swift ├── 1054. Distant Barcodes.swift ├── 1068. Product Sales Analysis I.sql ├── 1070. Product Sales Analysis III.sql ├── 1071. Greatest Common Divisor of Strings.swift ├── 1072. Flip Columns For Maximum Number of Equal Rows.swift ├── 1073. Adding Two Negabinary Numbers.swift ├── 1074. Number of Submatrices That Sum to Target.swift ├── 1075. Project Employees I.sql ├── 1078. Occurrences After Bigram.swift ├── 1079. Letter Tile Possibilities.swift ├── 1080. Insufficient Nodes in Root to Leaf Paths.swift ├── 1081. Smallest Subsequence of Distinct Characters.swift ├── 1089. Duplicate Zeros.swift ├── 1090. Largest Values From Labels.swift ├── 1091. Shortest Path in Binary Matrix.swift ├── 1093. Statistics from a Large Sample.swift ├── 1094. Car Pooling.swift ├── 1095. Find in Mountain Array.swift ├── 1096. Brace Expansion II.swift ├── 1103. Distribute Candies to People.swift ├── 1104. Path In Zigzag Labelled Binary Tree.swift ├── 1105. Filling Bookcase Shelves.swift ├── 1106. Parsing A Boolean Expression.swift ├── 1108. Defanging an IP Address.swift ├── 1109. Corporate Flight Bookings.swift ├── 1110. Delete Nodes And Return Forest.swift ├── 1111. Maximum Nesting Depth of Two Valid Parentheses Strings.swift ├── 1114. Print in Order.py ├── 1115. Print FooBar Alternately.py ├── 1116. Print Zero Even Odd.py ├── 1117. Building H2O.py ├── 1122. Relative Sort Array.swift ├── 1123. Lowest Common Ancestor of Deepest Leaves.swift ├── 1124. Longest Well-Performing Interval.swift ├── 1125. Smallest Sufficient Team.swift ├── 1128. Number of Equivalent Domino Pairs.swift ├── 1129. Shortest Path with Alternating Colors.swift ├── 1130. Minimum Cost Tree From Leaf Values.swift ├── 1131. Maximum of Absolute Value Expression.swift ├── 1137. N-th Tribonacci Number.swift ├── 1138. Alphabet Board Path.swift ├── 1139. Largest 1-Bordered Square.swift ├── 1143. Longest Common Subsequence.swift ├── 1144. Decrease Elements To Make Array Zigzag.swift ├── 1145. Binary Tree Coloring Game.swift ├── 1146. Snapshot Array.swift ├── 1147. Longest Chunked Palindrome Decomposition.swift ├── 1154. Day of the Year.swift ├── 1155. Number of Dice Rolls With Target Sum.swift ├── 1156. Swap For Longest Repeated Character Substring.swift ├── 1160. Find Words That Can Be Formed by Characters.swift ├── 1161. Maximum Level Sum of a Binary Tree.swift ├── 1162. As Far from Land as Possible.swift ├── 1163. Last Substring in Lexicographical Order.swift ├── 1164. Product Price at a Given Date.sql ├── 1169. Invalid Transactions.swift ├── 1170. Compare Strings by Frequency of the Smallest Character.swift ├── 1171. Remove Zero Sum Consecutive Nodes from Linked List.swift ├── 1174. Immediate Food Delivery II.sql ├── 1175. Prime Arrangements.swift ├── 1177. Can Make Palindrome from Substring.swift ├── 1178. Number of Valid Words for Each Puzzle.swift ├── 1179. Reformat Department Table.sql ├── 1184. Distance Between Bus Stops.swift ├── 1185. Day of the Week.swift ├── 1186. Maximum Subarray Sum with One Deletion.swift ├── 1189. Maximum Number of Balloons.swift ├── 1190. Reverse Substrings Between Each Pair of Parentheses.swift ├── 1192. Critical Connections in a Network.swift ├── 1193. Monthly Transactions I.sql ├── 1195. Fizz Buzz Multithreaded.py ├── 1200. Minimum Absolute Difference.swift ├── 1201. Ugly Number III.swift ├── 1202. Smallest String With Swaps.swift ├── 1203. Sort Items by Groups Respecting Dependencies.swift ├── 1204. Last Person to Fit in the Bus.sql ├── 1207. Unique Number of Occurrences.swift ├── 1208. Get Equal Substrings Within Budget.swift ├── 1209. Remove All Adjacent Duplicates in String II.swift ├── 1210. Minimum Moves to Reach Target with Rotations.swift ├── 1211. Queries Quality and Percentage.sql ├── 1217. Minimum Cost to Move Chips to The Same Position.swift ├── 1218. Longest Arithmetic Subsequence of Given Difference.swift ├── 1219. Path with Maximum Gold.swift ├── 1220. Count Vowels Permutation.swift ├── 1221. Split a String in Balanced Strings.swift ├── 1222. Queens That Can Attack the King.swift ├── 1223. Dice Roll Simulation.swift ├── 1226. The Dining Philosophers.py ├── 1227. Airplane Seat Assignment Probability.swift ├── 1232. Check If It Is a Straight Line.swift ├── 1233. Remove Sub-Folders from the Filesystem.swift ├── 1234. Replace the Substring for Balanced String.swift ├── 1235. Maximum Profit in Job Scheduling.swift ├── 1238. Circular Permutation in Binary Representation.swift ├── 1239. Maximum Length of a Concatenated String with Unique Characters.swift ├── 1247. Minimum Swaps to Make Strings Equal.swift ├── 1248. Count Number of Nice Subarrays.swift ├── 1249. Minimum Remove to Make Valid Parentheses.swift ├── 1250. Check If It Is a Good Array.swift ├── 1251. Average Selling Price.sql ├── 1252. Cells with Odd Values in a Matrix.swift ├── 1253. Reconstruct a 2-Row Binary Matrix.swift ├── 1254. Number of Closed Islands.swift ├── 1255. Maximum Score Words Formed by Letters.swift ├── 1260. Shift 2D Grid.swift ├── 1261. Find Elements in a Contaminated Binary Tree.swift ├── 1262. Greatest Sum Divisible by Three.swift ├── 1263. Minimum Moves to Move a Box to Their Target Location.swift ├── 1266. Minimum Time Visiting All Points.swift ├── 1267. Count Servers that Communicate.swift ├── 1268. Search Suggestions System.swift ├── 1269. Number of Ways to Stay in the Same Place After Some Steps.swift ├── 1275. Find Winner on a Tic Tac Toe Game.swift ├── 1276. Number of Burgers with No Waste of Ingredients.swift ├── 1277. Count Square Submatrices with All Ones.swift ├── 1278. Palindrome Partitioning III.swift ├── 1280. Students and Examinations.sql ├── 1281. Subtract the Product and Sum of Digits of an Integer.swift ├── 1282. Group the People Given the Group Size They Belong To.swift ├── 1283. Find the Smallest Divisor Given a Threshold.swift ├── 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix.swift ├── 1286. Iterator for Combination.swift ├── 1287. Element Appearing More Than 25% In Sorted Array.swift ├── 1288. Remove Covered Intervals.swift ├── 1290. Convert Binary Number in a Linked List to Integer.swift ├── 1291. Sequential Digits.swift ├── 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold.swift ├── 1293. Shortest Path in a Grid with Obstacles Elimination.swift ├── 1295. Find Numbers with Even Number of Digits.swift ├── 1296. Divide Array in Sets of K Consecutive Numbers.swift ├── 1297. Maximum Number of Occurrences of a Substring.swift ├── 1298. Maximum Candies You Can Get from Boxes.swift ├── 1299. Replace Elements with Greatest Element on Right Side.swift ├── 1300. Sum of Mutated Array Closest to Target.swift ├── 1301. Number of Paths with Max Score.swift ├── 1302. Deepest Leaves Sum.swift ├── 1304. Find N Unique Integers Sum up to Zero.swift ├── 1305. All Elements in Two Binary Search Trees.swift ├── 1306. Jump Game III.swift ├── 1309. Decrypt String from Alphabet to Integer Mapping.swift ├── 1310. XOR Queries of a Subarray.swift ├── 1311. Get Watched Videos by Your Friends.swift ├── 1312. Minimum Insertion Steps to Make a String Palindrome.swift ├── 1313. Decompress Run-Length Encoded List.swift ├── 1314. Matrix Block Sum.swift ├── 1315. Sum of Nodes with Even-Valued Grandparent.swift ├── 1317. Convert Integer to the Sum of Two No-Zero Integers.swift ├── 1318. Minimum Flips to Make a OR b Equal to c.swift ├── 1319. Number of Operations to Make Network Connected.swift ├── 1320. Minimum Distance to Type a Word Using Two Fingers.swift ├── 1321. Restaurant Growth.sql ├── 1323. Maximum 69 Number.swift ├── 1324. Print Words Vertically.swift ├── 1325. Delete Leaves With a Given Value.swift ├── 1326. Minimum Number of Taps to Open to Water a Garden.swift ├── 1327. List the Products Ordered in a Period.sql ├── 1328. Break a Palindrome.swift ├── 1329. Sort the Matrix Diagonally.swift ├── 1330. Reverse Subarray To Maximize Array Value.swift ├── 1331. Rank Transform of an Array.swift ├── 1332. Remove Palindromic Subsequences.swift ├── 1333. Filter Restaurants by Vegan-Friendly, Price and Distance.swift ├── 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance.swift ├── 1335. Minimum Difficulty of a Job Schedule.swift ├── 1337. The K Weakest Rows in a Matrix.swift ├── 1338. Reduce Array Size to The Half.swift ├── 1340. Jump Game V.swift ├── 1341. Movie Rating.sql ├── 1342. Number of Steps to Reduce a Number to Zero.swift ├── 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold.swift ├── 1344. Angle Between Hands of a Clock.swift ├── 1345. Jump Game IV.swift ├── 1346. Check If N and Its Double Exist.swift ├── 1347. Minimum Number of Steps to Make Two Strings Anagram.swift ├── 1348. Tweet Counts Per Frequency.swift ├── 1349. Maximum Students Taking Exam.swift ├── 1351. Count Negative Numbers in a Sorted Matrix.swift ├── 1352. Product of the Last K Numbers.swift ├── 1354. Construct Target Array With Multiple Sums.swift ├── 1356. Sort Integers by The Number of 1 Bits.swift ├── 1357. Apply Discount Every n Orders.swift ├── 1358. Number of Substrings Containing All Three Characters.swift ├── 1359. Count All Valid Pickup and Delivery Options.swift ├── 1360. Number of Days Between Two Dates.swift ├── 1361. Validate Binary Tree Nodes.swift ├── 1362. Closest Divisors.swift ├── 1363. Largest Multiple of Three.swift ├── 1365. How Many Numbers Are Smaller Than the Current Number.swift ├── 1366. Rank Teams by Votes.swift ├── 1367. Linked List in Binary Tree.swift ├── 1368. Minimum Cost to Make at Least One Valid Path in a Grid.swift ├── 1370. Increasing Decreasing String.swift ├── 1371. Find the Longest Substring Containing Vowels in Even Counts.swift ├── 1372. Longest ZigZag Path in a Binary Tree.swift ├── 1373. Maximum Sum BST in Binary Tree.swift ├── 1374. Generate a String With Characters That Have Odd Counts.swift ├── 1375. Bulb Switcher III.swift ├── 1376. Time Needed to Inform All Employees.swift ├── 1377. Frog Position After T Seconds.swift ├── 1378. Replace Employee ID With The Unique Identifier.sql ├── 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree.java ├── 1380. Lucky Numbers in a Matrix.swift ├── 1381. Design a Stack With Increment Operation.swift ├── 1382. Balance a Binary Search Tree.swift ├── 1383. Maximum Performance of a Team.swift ├── 1385. Find the Distance Value Between Two Arrays.swift ├── 1386. Cinema Seat Allocation.swift ├── 1387. Sort Integers by The Power Value.swift ├── 1388. Pizza With 3n Slices.swift ├── 1389. Create Target Array in the Given Order.swift ├── 1390. Four Divisors.swift ├── 1391. Check if There is a Valid Path in a Grid.swift ├── 1392. Longest Happy Prefix.swift ├── 1394. Find Lucky Integer in an Array.swift ├── 1395. Count Number of Teams.swift ├── 1396. Design Underground System.swift ├── 1399. Count Largest Group.swift ├── 1400. Construct K Palindrome Strings.swift ├── 1402. Reducing Dishes.swift ├── 1403. Minimum Subsequence in Non-Increasing Order.swift ├── 1404. Number of Steps to Reduce a Number in Binary Representation to One.swift ├── 1405. Longest Happy String.swift ├── 1406. Stone Game III.swift ├── 1408. String Matching in an Array.swift ├── 1409. Queries on a Permutation With Key.swift ├── 1410. HTML Entity Parser.swift ├── 1411. Number of Ways to Paint N × 3 Grid.swift ├── 1413. Minimum Value to Get Positive Step by Step Sum.swift ├── 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K.swift ├── 1415. The k-th Lexicographical String of All Happy Strings of Length n.swift ├── 1417. Reformat The String.swift ├── 1418. Display Table of Food Orders in a Restaurant.swift ├── 1419. Minimum Number of Frogs Croaking.swift ├── 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons.swift ├── 1422. Maximum Score After Splitting a String.swift ├── 1423. Maximum Points You Can Obtain from Cards.swift ├── 1424. Diagonal Traverse II.swift ├── 1425. Constrained Subsequence Sum.swift ├── 1431. Kids With the Greatest Number of Candies.swift ├── 1432. Max Difference You Can Get From Changing an Integer.swift ├── 1433. Check If a String Can Break Another String.swift ├── 1434. Number of Ways to Wear Different Hats to Each Other.swift ├── 1436. Destination City.swift ├── 1437. Check If All 1's Are at Least Length K Places Away.swift ├── 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.swift ├── 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows.swift ├── 1441. Build an Array With Stack Operations.swift ├── 1442. Count Triplets That Can Form Two Arrays of Equal XOR.swift ├── 1443. Minimum Time to Collect All Apples in a Tree.swift ├── 1446. Consecutive Characters.swift ├── 1447. Simplified Fractions.swift ├── 1448. Count Good Nodes in Binary Tree.swift ├── 1449. Form Largest Integer With Digits That Add up to Target.swift ├── 1450. Number of Students Doing Homework at a Given Time.swift ├── 1451. Rearrange Words in a Sentence.swift ├── 1452. People Whose List of Favorite Companies Is Not a Subset of Another List.swift ├── 1453. Maximum Number of Darts Inside of a Circular Dartboard.swift ├── 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence.swift ├── 1456. Maximum Number of Vowels in a Substring of Given Length.swift ├── 1457. Pseudo-Palindromic Paths in a Binary Tree.swift ├── 1458. Max Dot Product of Two Subsequences.swift ├── 1460. Make Two Arrays Equal by Reversing Sub-arrays.swift ├── 1461. Check If a String Contains All Binary Codes of Size K.swift ├── 1462. Course Schedule IV.swift ├── 1463. Cherry Pickup II.swift ├── 1464. Maximum Product of Two Elements in an Array.swift ├── 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.swift ├── 1466. Reorder Routes to Make All Paths Lead to the City Zero.swift ├── 1470. Shuffle the Array.swift ├── 1471. The k Strongest Values in an Array.swift ├── 1472. Design Browser History.swift ├── 1473. Paint House III.swift ├── 1475. Final Prices With a Special Discount in a Shop.swift ├── 1476. Subrectangle Queries.swift ├── 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum.swift ├── 1478. Allocate Mailboxes.swift ├── 1480. Running Sum of 1d Array.swift ├── 1481. Least Number of Unique Integers after K Removals.swift ├── 1482. Minimum Number of Days to Make m Bouquets.swift ├── 1483. Kth Ancestor of a Tree Node.swift ├── 1486. XOR Operation in an Array.swift ├── 1487. Making File Names Unique.swift ├── 1488. Avoid Flood in The City.swift ├── 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree.swift ├── 1491. Average Salary Excluding the Minimum and Maximum Salary.swift ├── 1492. The kth Factor of n.swift ├── 1493. Longest Subarray of 1's After Deleting One Element.swift ├── 1496. Path Crossing.swift ├── 1497. Check If Array Pairs Are Divisible by k.swift ├── 1498. Number of Subsequences That Satisfy the Given Sum Condition.swift └── 1499. Max Value of Equation.swift ├── 1501-2000 ├── 1502. Can Make Arithmetic Progression From Sequence.swift ├── 1503. Last Moment Before All Ants Fall Out of a Plank.swift ├── 1504. Count Submatrices With All Ones.swift ├── 1507. Reformat Date.swift ├── 1508. Range Sum of Sorted Subarray Sums.swift ├── 1509. Minimum Difference Between Largest and Smallest Value in Three Moves.swift ├── 1510. Stone Game IV.swift ├── 1512. Number of Good Pairs.swift ├── 1513. Number of Substrings With Only 1s.swift ├── 1514. Path with Maximum Probability.swift ├── 1515. Best Position for a Service Centre.swift ├── 1517. Find Users With Valid E-Mails.sql ├── 1518. Water Bottles.swift ├── 1523. Count Odd Numbers in an Interval Range.swift ├── 1524. Number of Sub-arrays With Odd Sum.swift ├── 1525. Number of Good Ways to Split a String.swift ├── 1526. Minimum Number of Increments on Subarrays to Form a Target Array.swift ├── 1528. Shuffle String.swift ├── 1529. Bulb Switcher IV.swift ├── 1530. Number of Good Leaf Nodes Pairs.swift ├── 1531. String Compression II.swift ├── 1534. Count Good Triplets.swift ├── 1535. Find the Winner of an Array Game.swift ├── 1536. Minimum Swaps to Arrange a Binary Grid.swift ├── 1537. Get the Maximum Score.swift ├── 1539. Kth Missing Positive Number.swift ├── 1540. Can Convert String in K Moves.swift ├── 1541. Minimum Insertions to Balance a Parentheses String.swift ├── 1542. Find Longest Awesome Substring.swift ├── 1544. Make The String Great.swift ├── 1545. Find Kth Bit in Nth Binary String.swift ├── 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target.swift ├── 1547. Minimum Cost to Cut a Stick.swift ├── 1550. Three Consecutive Odds.swift ├── 1551. Minimum Operations to Make Array Equal.swift ├── 1552. Magnetic Force Between Two Balls.swift ├── 1553. Minimum Number of Days to Eat N Oranges.swift ├── 1556. Thousand Separator.swift ├── 1557. Minimum Number of Vertices to Reach All Nodes.swift ├── 1558. Minimum Numbers of Function Calls to Make Target Array.swift ├── 1559. Detect Cycles in 2D Grid.swift ├── 1560. Most Visited Sector in a Circular Track.swift ├── 1561. Maximum Number of Coins You Can Get.swift ├── 1562. Find Latest Group of Size M.swift ├── 1563. Stone Game V.swift ├── 1566. Detect Pattern of Length M Repeated K or More Times.swift ├── 1567. Maximum Length of Subarray With Positive Product.swift ├── 1572. Matrix Diagonal Sum.swift ├── 1573. Number of Ways to Split a String.swift ├── 1574. Shortest Subarray to be Removed to Make Array Sorted.swift ├── 1575. Count All Possible Routes.swift ├── 1576. Replace Alls to Avoid Consecutive Repeating Characters.swift ├── 1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers.swift ├── 1578. Minimum Deletion Cost to Avoid Repeating Letters.swift ├── 1579. Remove Max Number of Edges to Keep Graph Fully Traversable.swift ├── 1582. Special Positions in a Binary Matrix.swift ├── 1583. Count Unhappy Friends.swift ├── 1584. Min Cost to Connect All Points.swift ├── 1588. Sum of All Odd Length Subarrays.swift ├── 1589. Maximum Sum Obtained of Any Permutation.swift ├── 1590. Make Sum Divisible by P.swift ├── 1592. Rearrange Spaces Between Words.swift ├── 1593. Split a String Into the Max Number of Unique Substrings.swift ├── 1594. Maximum Non Negative Product in a Matrix.swift ├── 1598. Crawler Log Folder.swift ├── 1599. Maximum Profit of Operating a Centennial Wheel.swift ├── 1600. Throne Inheritance.swift ├── 1603. Design Parking System.swift ├── 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period.swift ├── 1605. Find Valid Matrix Given Row and Column Sums.swift ├── 1608. Special Array With X Elements Greater Than or Equal X.swift ├── 1609. Even Odd Tree.swift ├── 1610. Maximum Number of Visible Points.swift ├── 1611. Minimum One Bit Operations to Make Integers Zero.swift ├── 1614. Maximum Nesting Depth of the Parentheses.swift ├── 1615. Maximal Network Rank.swift ├── 1616. Split Two Strings to Make Palindrome.swift ├── 1617. Count Subtrees With Max Distance Between Cities.swift ├── 1619. Mean of Array After Removing Some Elements.swift ├── 1620. Coordinate With Maximum Network Quality.swift ├── 1621. Number of Sets of K Non-Overlapping Line Segments.swift ├── 1622. Fancy Sequence.swift ├── 1624. Largest Substring Between Two Equal Characters.swift ├── 1625. Lexicographically Smallest String After Applying Operations.swift ├── 1626. Best Team With No Conflicts.swift ├── 1627. Graph Connectivity With Threshold.swift ├── 1629. Slowest Key.swift ├── 1630. Arithmetic Subarrays.swift ├── 1631. Path With Minimum Effort.swift ├── 1633. Percentage of Users Attended a Contest.sql ├── 1636. Sort Array by Increasing Frequency.swift ├── 1637. Widest Vertical Area Between Two Points Containing No Points.swift ├── 1638. Count Substrings That Differ by One Character.swift ├── 1639. Number of Ways to Form a Target String Given a Dictionary.swift ├── 1640. Check Array Formation Through Concatenation.swift ├── 1641. Count Sorted Vowel Strings.swift ├── 1642. Furthest Building You Can Reach.swift ├── 1643. Kth Smallest Instructions.swift ├── 1646. Get Maximum in Generated Array.swift ├── 1647. Minimum Deletions to Make Character Frequencies Unique.swift ├── 1648. Sell Diminishing-Valued Colored Balls.swift ├── 1649. Create Sorted Array through Instructions.swift ├── 1652. Defuse the Bomb.swift ├── 1653. Minimum Deletions to Make String Balanced.swift ├── 1654. Minimum Jumps to Reach Home.swift ├── 1656. Design an Ordered Stream.swift ├── 1657. Determine if Two Strings Are Close.swift ├── 1658. Minimum Operations to Reduce X to Zero.swift ├── 1661. Average Time of Process per Machine.sql ├── 1662. Check If Two String Arrays are Equivalent.swift ├── 1663. Smallest String With A Given Numeric Value.swift ├── 1664. Ways to Make a Fair Array.swift ├── 1665. Minimum Initial Energy to Finish Tasks.swift ├── 1668. Maximum Repeating Substring.swift ├── 1669. Merge In Between Linked Lists.swift ├── 1670. Design Front Middle Back Queue.swift ├── 1672. Richest Customer Wealth.swift ├── 1673. Find the Most Competitive Subsequence.swift ├── 1674. Minimum Moves to Make Array Complementary.swift ├── 1675. Minimize Deviation in Array.swift ├── 1678. Goal Parser Interpretation.swift ├── 1679. Max Number of K-Sum Pairs.swift ├── 1680. Concatenation of Consecutive Binary Numbers.swift ├── 1683. Invalid Tweets.sql ├── 1684. Count the Number of Consistent Strings.swift ├── 1685. Sum of Absolute Differences in a Sorted Array.swift ├── 1686. Stone Game VI.swift ├── 1687. Delivering Boxes from Storage to Ports.swift ├── 1688. Count of Matches in Tournament.swift ├── 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers.swift ├── 1690. Stone Game VII.swift ├── 1691. Maximum Height by Stacking Cuboids.swift ├── 1694. Reformat Phone Number.swift ├── 1695. Maximum Erasure Value.swift ├── 1696. Jump Game VI.swift ├── 1697. Checking Existence of Edge Length Limited Paths.swift ├── 1700. Number of Students Unable to Eat Lunch.swift ├── 1701. Average Waiting Time.swift ├── 1702. Maximum Binary String After Change.swift ├── 1704. Determine if String Halves Are Alike.swift ├── 1706. Where Will the Ball Fall.swift ├── 1710. Maximum Units on a Truck.swift ├── 1711. Count Good Meals.swift ├── 1712. Ways to Split Array Into Three Subarrays.swift ├── 1716. Calculate Money in Leetcode Bank.swift ├── 1717. Maximum Score From Removing Substrings.swift ├── 1718. Construct the Lexicographically Largest Valid Sequence.swift ├── 1720. Decode XORed Array.swift ├── 1721. Swapping Nodes in a Linked List.swift ├── 1722. Minimize Hamming Distance After Swap Operations.swift ├── 1723. Find Minimum Time to Finish All Jobs.swift ├── 1725. Number Of Rectangles That Can Form The Largest Square.swift ├── 1726. Tuple with Same Product.swift ├── 1727. Largest Submatrix With Rearrangements.swift ├── 1731. The Number of Employees Which Report to Each Employee.sql ├── 1732. Find the Highest Altitude.swift ├── 1733. Minimum Number of People to Teach.swift ├── 1734. Decode XORed Permutation.swift ├── 1736. Latest Time by Replacing Hidden Digits.swift ├── 1737. Change Minimum Characters to Satisfy One of Three Conditions.swift ├── 1738. Find Kth Largest XOR Coordinate Value.swift ├── 1739. Building Boxes.swift ├── 1742. Maximum Number of Balls in a Box.swift ├── 1743. Restore the Array From Adjacent Pairs.swift ├── 1744. Can You Eat Your Favorite Candy on Your Favorite Day.swift ├── 1745. Palindrome Partitioning IV.swift ├── 1748. Sum of Unique Elements.swift ├── 1749. Maximum Absolute Sum of Any Subarray.swift ├── 1750. Minimum Length of String After Deleting Similar Ends.swift ├── 1752. Check if Array Is Sorted and Rotated.swift ├── 1753. Maximum Score From Removing Stones.swift ├── 1754. Largest Merge Of Two Strings.swift ├── 1758. Minimum Changes To Make Alternating Binary String.swift ├── 1759. Count Number of Homogenous Substrings.swift ├── 1760. Minimum Limit of Balls in a Bag.swift ├── 1761. Minimum Degree of a Connected Trio in a Graph.swift ├── 1763. Longest Nice Substring.swift ├── 1764. Form Array by Concatenating Subarrays of Another Array.swift ├── 1765. Map of Highest Peak.swift ├── 1766. Tree of Coprimes.swift ├── 1768. Merge Strings Alternately.swift ├── 1769. Minimum Number of Operations to Move All Balls to Each Box.swift ├── 1770. Maximum Score from Performing Multiplication Operations.swift ├── 1771. Maximize Palindrome Length From Subsequences.swift ├── 1773. Count Items Matching a Rule.swift ├── 1774. Closest Dessert Cost.swift ├── 1775. Equal Sum Arrays With Minimum Number of Operations.swift ├── 1779. Find Nearest Point That Has the Same X or Y Coordinate.swift ├── 1780. Check if Number is a Sum of Powers of Three.swift ├── 1781. Sum of Beauty of All Substrings.swift ├── 1784. Check if Binary String Has at Most One Segment of Ones.swift ├── 1785. Minimum Elements to Add to Form a Given Sum.swift ├── 1789. Primary Department for Each Employee.sql ├── 1790. Check if One String Swap Can Make Strings Equal.swift ├── 1791. Find Center of Star Graph.swift ├── 1796. Second Largest Digit in a String.swift ├── 1798. Maximum Number of Consecutive Values You Can Make.swift ├── 1799. Maximize Score After N Operations.swift ├── 1800. Maximum Ascending Subarray Sum.swift ├── 1801. Number of Orders in the Backlog.swift ├── 1802. Maximum Value at a Given Index in a Bounded Array.swift ├── 1805. Number of Different Integers in a String.swift ├── 1806. Minimum Number of Operations to Reinitialize a Permutation.swift ├── 1807. Evaluate the Bracket Pairs of a String.swift ├── 1808. Maximize Number of Nice Divisors.swift ├── 1812. Determine Color of a Chessboard Square.swift ├── 1813. Sentence Similarity III.swift ├── 1814. Count Nice Pairs in an Array.swift ├── 1815. Maximum Number of Groups Getting Fresh Donuts.swift ├── 1816. Truncate Sentence.swift ├── 1817. Finding the Users Active Minutes.swift ├── 1818. Minimum Absolute Sum Difference.swift ├── 1819. Number of Different Subsequences GCDs.swift ├── 1822. Sign of the Product of an Array.swift ├── 1823. Find the Winner of the Circular Game.swift ├── 1824. Minimum Sideway Jumps.swift ├── 1825. Finding MK Average.swift ├── 1827. Minimum Operations to Make the Array Increasing.swift ├── 1828. Queries on Number of Points Inside a Circle.swift ├── 1829. Maximum XOR for Each Query.swift ├── 1832. Check if the Sentence Is Pangram.swift ├── 1833. Maximum Ice Cream Bars.swift ├── 1835. Find XOR Sum of All Pairs Bitwise AND.swift ├── 1837. Sum of Digits in Base K.swift ├── 1838. Frequency of the Most Frequent Element.swift ├── 1839. Longest Substring Of All Vowels in Order.swift ├── 1840. Maximum Building Height.swift ├── 1844. Replace All Digits with Characters.swift ├── 1845. Seat Reservation Manager.swift ├── 1846. Maximum Element After Decreasing and Rearranging.swift ├── 1848. Minimum Distance to the Target Element.swift ├── 1849. Splitting a String Into Descending Consecutive Values.swift ├── 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number.swift ├── 1854. Maximum Population Year.swift ├── 1855. Maximum Distance Between a Pair of Values.swift ├── 1856. Maximum Subarray Min-Product.swift ├── 1857. Largest Color Value in a Directed Graph.swift ├── 1859. Sorting the Sentence.swift ├── 1860. Incremental Memory Leak.swift ├── 1861. Rotating the Box.swift ├── 1862. Sum of Floored Pairs.swift ├── 1863. Sum of All Subset XOR Totals.swift ├── 1864. Minimum Number of Swaps to Make the Binary String Alternating.swift ├── 1865. Finding Pairs With a Certain Sum.swift ├── 1866. Number of Ways to Rearrange Sticks With K Sticks Visible.swift ├── 1869. Longer Contiguous Segments of Ones than Zeros.swift ├── 1870. Minimum Speed to Arrive on Time.swift ├── 1871. Jump Game VII.swift ├── 1872. Stone Game VIII.swift ├── 1876. Substrings of Size Three with Distinct Characters.swift ├── 1877. Minimize Maximum Pair Sum in Array.swift ├── 1878. Get Biggest Three Rhombus Sums in a Grid.swift ├── 1879. Minimum XOR Sum of Two Arrays.swift ├── 1880. Check if Word Equals Summation of Two Words.swift ├── 1881. Maximum Value after Insertion.swift ├── 1883. Minimum Skips to Arrive at Meeting On Time.swift ├── 1884. Egg Drop With 2 Eggs and N Floors.swift ├── 1886. Determine Whether Matrix Can Be Obtained By Rotation.swift ├── 1887. Reduction Operations to Make the Array Elements Equal.swift ├── 1888. Minimum Number of Flips to Make the Binary String Alternating.swift ├── 1889. Minimum Space Wasted From Packaging.swift ├── 1893. Check if All the Integers in a Range Are Covered.swift ├── 1894. Find the Student that Will Replace the Chalk.swift ├── 1895. Largest Magic Square.swift ├── 1896. Minimum Cost to Change the Final Value of Expression.swift ├── 1897. Redistribute Characters to Make All Strings Equal.swift ├── 1898. Maximum Number of Removable Characters.swift ├── 1899. Merge Triplets to Form Target Triplet.swift ├── 1901. Find a Peak Element II.swift ├── 1903. Largest Odd Number in String.swift ├── 1904. The Number of Full Rounds You Have Played.swift ├── 1905. Count Sub Islands.swift ├── 1906. Minimum Absolute Difference Queries.swift ├── 1907. Count Salary Categories.sql ├── 1909. Remove One Element to Make the Array Strictly Increasing.swift ├── 1910. Remove All Occurrences of a Substring.swift ├── 1911. Maximum Alternating Subsequence Sum.swift ├── 1913. Maximum Product Difference Between Two Pairs.swift ├── 1914. Cyclically Rotating a Grid.swift ├── 1915. Number of Wonderful Substrings.swift ├── 1916. Count Ways to Build Rooms in an Ant Colony.swift ├── 1920. Build Array from Permutation.swift ├── 1921. Eliminate Maximum Number of Monsters.swift ├── 1922. Count Good Numbers.swift ├── 1923. Longest Common Subpath.swift ├── 1925. Count Square Sum Triples.swift ├── 1926. Nearest Exit from Entrance in Maze.swift ├── 1927. Sum Game.swift ├── 1928. Minimum Cost to Reach Destination in Time.swift ├── 1929. Concatenation of Array.swift ├── 1930. Unique Length-3 Palindromic Subsequences.swift ├── 1931. Painting a Grid With Three Different Colors.swift ├── 1932. Merge BSTs to Create Single BST.swift ├── 1934. Confirmation Rate.sql ├── 1935. Maximum Number of Words You Can Type.swift ├── 1936. Add Minimum Number of Rungs.swift ├── 1937. Maximum Number of Points with Cost.swift ├── 1941. Check if All Characters Have Equal Number of Occurrences.swift ├── 1942. The Number of the Smallest Unoccupied Chair.swift ├── 1943. Describe the Painting.swift ├── 1944. Number of Visible People in a Queue.swift ├── 1945. Sum of Digits of String After Convert.swift ├── 1946. Largest Number After Mutating Substring.swift ├── 1947. Maximum Compatibility Score Sum.swift ├── 1948. Delete Duplicate Folders in System.swift ├── 1952. Three Divisors.swift ├── 1953. Maximum Number of Weeks for Which You Can Work.swift ├── 1954. Minimum Garden Perimeter to Collect Enough Apples.swift ├── 1955. Count Number of Special Subsequences.swift ├── 1961. Check If String Is a Prefix of Array.swift ├── 1963. Minimum Number of Swaps to Make the String Balanced.swift ├── 1964. Find the Longest Valid Obstacle Course at Each Position.swift ├── 1970. Last Day Where You Can Still Cross.swift └── 1978. Employees Whose Manager Left the Company.sql ├── 2001-2500 ├── 2239. Find Closest Number to Zero.swift ├── 2240. Number of Ways to Buy Pens and Pencils.swift ├── 2241. Design an ATM Machine.swift ├── 2242. Maximum Score of a Node Sequence.swift ├── 2356. Number of Unique Subjects Taught by Each Teacher.sql ├── 2392. Build a Matrix With Conditions.swift ├── 2412. Minimum Money Required Before Transactions.swift ├── 2413. Smallest Even Multiple.swift ├── 2471. Minimum Number of Operations to Sort a Binary Tree by Level.swift ├── 2484. Count Palindromic Subsequences.swift ├── 2496. Maximum Value of a String in an Array.swift ├── 2497. Maximum Star Sum of a Graph.swift ├── 2498. Frog Jump II.swift └── 2499. Minimum Total Cost to Make Arrays Unequal.swift ├── 2501-3000 ├── 2508. Add Edges to Make Degrees of All Nodes Even.swift ├── 2512. Reward Top K Students.swift ├── 2513. Minimize the Maximum of Two Arrays.swift ├── 2514. Count Anagrams.swift ├── 2516. Take K of Each Character From Left and Right.swift ├── 2517. Maximum Tastiness of Candy Basket.swift ├── 2518. Number of Great Partitions.swift ├── 2521. Distinct Prime Factors of Product of Array.swift ├── 2522. Partition String Into Substrings With Values at Most K.swift ├── 2523. Closest Prime Numbers in Range.swift ├── 2525. Categorize Box According to Criteria.swift ├── 2526. Find Consecutive Integers from a Data Stream.swift ├── 2527. Find Xor-Beauty of Array.swift ├── 2528. Maximize the Minimum Powered City.swift ├── 2529. Maximum Count of Positive Integer and Negative Integer.swift ├── 2530. Maximal Score After Applying K Operations.swift ├── 2531. Make Number of Distinct Characters Equal.swift ├── 2532. Time to Cross a Bridge.swift ├── 2535. Difference Between Element Sum and Digit Sum of an Array.swift ├── 2536. Increment Submatrices by One.swift ├── 2537. Count the Number of Good Subarrays.swift ├── 2538. Difference Between Maximum and Minimum Price Sum.swift ├── 2540. Minimum Common Value.swift ├── 2541. Minimum Operations to Make Array Equal II.swift ├── 2542. Maximum Subsequence Score.swift ├── 2543. Check if Point Is Reachable.swift ├── 2544. Alternating Digit Sum.swift ├── 2545. Sort the Students by Their Kth Score.swift ├── 2546. Apply Bitwise Operations to Make Strings Equal.swift ├── 2547. Minimum Cost to Split an Array.swift ├── 2549. Count Distinct Numbers on Board.swift ├── 2550. Count Collisions of Monkeys on a Polygon.swift ├── 2551. Put Marbles in Bags.swift ├── 2552. Count Increasing Quadruplets.swift ├── 2553. Separate the Digits in an Array.swift ├── 2554. Maximum Number of Integers to Choose From a Range I.swift ├── 2555. Maximize Win From Two Segments.swift ├── 2556. Disconnect Path in a Binary Matrix by at Most One Flip.swift ├── 2558. Take Gifts From the Richest Pile.swift ├── 2559. Count Vowel Strings in Ranges.swift ├── 2560. House Robber IV.swift ├── 2561. Rearranging Fruits.swift ├── 2562. Find the Array Concatenation Value.swift ├── 2563. Count the Number of Fair Pairs.swift ├── 2565. Subsequence With the Minimum Score.swift ├── 2566. Maximum Difference by Remapping a Digit.swift ├── 2567. Minimum Score by Changing Two Elements.swift ├── 2568. Minimum Impossible OR.swift ├── 2570. Merge Two 2D Arrays by Summing Values.swift ├── 2571. Minimum Operations to Reduce an Integer to 0.swift ├── 2572. Count the Number of Square-Free Subsets.swift ├── 2573. Find the String with LCP.swift ├── 2574. Left and Right Sum Differences.swift ├── 2577. Minimum Time to Visit a Cell In a Grid.swift ├── 2581. Count Number of Possible Root Nodes.swift ├── 2582. Pass the Pillow.swift ├── 2584. Split the Array to Make Coprime Products.swift ├── 2585. Number of Ways to Earn Points.swift ├── 2586. Count the Number of Vowel Strings in Range.swift ├── 2589. Minimum Time to Complete All Tasks.swift ├── 2595. Number of Even and Odd Bits.swift ├── 2600. K Items With the Maximum Sum.swift ├── 2601. Prime Subtraction Operation.swift ├── 2602. Minimum Operations to Make All Array Elements Equal.swift ├── 2603. Collect Coins in a Tree.swift ├── 2605. Form Smallest Number From Two Digit Arrays.swift ├── 2606. Find the Substring With Maximum Cost.swift ├── 2607. Make K-Subarray Sums Equal.swift ├── 2608. Shortest Cycle in a Graph.swift ├── 2610. Convert an Array Into a 2D Array With Conditions.swift ├── 2611. Mice and Cheese.swift ├── 2612. Minimum Reverse Operations.swift ├── 2615. Sum of Distances.swift ├── 2616. Minimize the Maximum Difference of Pairs.swift ├── 2618. Check if Object Instance of Class.ts ├── 2619. Array Prototype Last.ts ├── 2620. Counter.ts ├── 2621. Sleep.ts ├── 2622. Cache With Time Limit.ts ├── 2623. Memoize.ts ├── 2625. Flatten Deeply Nested Array.ts ├── 2627. Debounce.ts ├── 2628. JSON Deep Equal.ts ├── 2629. Function Composition.ts ├── 2631. Group By.ts ├── 2632. Curry.ts ├── 2633. Convert Object to JSON String.ts ├── 2634. Filter Elements from Array.ts ├── 2635. Apply Transform Over Each Element in Array.ts ├── 2640. Find the Score of All Prefixes of an Array.swift ├── 2642. Design Graph With Shortest Path Calculator.swift ├── 2645. Minimum Additions to Make Valid String.swift ├── 2646. Minimize the Total Price of the Trips.swift ├── 2653. Sliding Subarray Beauty.swift ├── 2654. Minimum Number of Operations to Make All Array Elements Equal to 1.swift ├── 2657. Find the Prefix Common Array of Two Arrays.swift ├── 2658. Maximum Number of Fish in a Grid.swift ├── 2659. Make Array Empty.swift ├── 2661. First Completely Painted Row or Column.swift ├── 2662. Minimum Cost of a Path With Special Roads.swift ├── 2663. Lexicographically Smallest Beautiful String.swift ├── 2671. Frequency Tracker.swift ├── 2672. Number of Adjacent Elements With the Same Color.swift ├── 2673. Make Costs of Paths Equal in a Binary Tree.swift ├── 2679. Sum in a Matrix.swift ├── 2680. Maximum OR.swift ├── 2681. Power of Heroes.swift ├── 2683. Neighboring Bitwise XOR.swift ├── 2684. Maximum Number of Moves in a Grid.swift ├── 2685. Count the Number of Complete Components.swift ├── 2706. Buy Two Chocolates.swift ├── 2707. Extra Characters in a String.swift ├── 2708. Maximum Strength of a Group.swift ├── 2709. Greatest Common Divisor Traversal.swift ├── 2711. Difference of Number of Distinct Values on Diagonals.swift ├── 2712. Minimum Cost to Make All Characters Equal.swift ├── 2713. Maximum Strictly Increasing Cells in a Matrix.swift ├── 2716. Minimize String Length.swift ├── 2717. Semi-Ordered Permutation.swift ├── 2718. Sum of Matrix After Queries.swift ├── 2719. Count of Integers.swift ├── 2729. Check if The Number is Fascinating.swift ├── 2730. Find the Longest Semi-Repetitive Substring.swift ├── 2731. Movement of Robots.swift ├── 2732. Find a Good Subset of the Matrix.swift ├── 2733. Neither Minimum nor Maximum.swift ├── 2734. Lexicographically Smallest String After Substring Operation.swift ├── 2735. Collecting Chocolates.swift ├── 2736. Maximum Sum Queries.swift ├── 2739. Total Distance Traveled.swift ├── 2740. Find the Value of the Partition.swift ├── 2741. Special Permutations.swift ├── 2742. Painting the Walls.swift ├── 2745. Construct the Longest New String.swift ├── 2746. Decremental String Concatenation.swift ├── 2747. Count Zero Request Servers.swift ├── 2749. Minimum Operations to Make the Integer Zero.swift ├── 2750. Ways to Split Array Into Good Subarrays.swift ├── 2751. Robot Collisions.swift ├── 2760. Longest Even Odd Subarray With Threshold.swift ├── 2761. Prime Pairs With Target Sum.swift ├── 2762. Continuous Subarrays.swift ├── 2763. Sum of Imbalance Numbers of All Subarrays.swift ├── 2765. Longest Alternating Subarray.swift ├── 2766. Relocate Marbles.swift ├── 2767. Partition String Into Minimum Beautiful Substrings.swift ├── 2768. Number of Black Blocks.swift ├── 2769. Find the Maximum Achievable Number.swift ├── 2770. Maximum Number of Jumps to Reach the Last Index.swift ├── 2771. Longest Non-decreasing Subarray From Two Arrays.swift ├── 2772. Apply Operations to Make All Array Elements Equal to Zero.swift ├── 2778. Sum of Squares of Special Elements.swift ├── 2779. Maximum Beauty of an Array After Applying Operation.swift ├── 2780. Minimum Index of a Valid Split.swift ├── 2781. Length of the Longest Valid Substring.swift ├── 2784. Check if Array is Good.swift ├── 2785. Sort Vowels in a String.swift ├── 2786. Visit Array Positions to Maximize Score.swift ├── 2787. Ways to Express an Integer as Sum of Powers.swift ├── 2788. Split Strings by Separator.swift ├── 2789. Largest Element in an Array after Merge Operations.swift ├── 2790. Maximum Number of Groups With Increasing Length.swift ├── 2791. Count Paths That Can Form a Palindrome in a Tree.swift ├── 2798. Number of Employees Who Met the Target.swift ├── 2799. Count Complete Subarrays in an Array.swift ├── 2800. Shortest String That Contains Three Strings.swift ├── 2801. Count Stepping Numbers in Range.swift ├── 2806. Account Balance After Rounded Purchase.swift ├── 2807. Insert Greatest Common Divisors in Linked List.swift ├── 2808. Minimum Seconds to Equalize a Circular Array.swift ├── 2809. Minimum Time to Make Array Sum At Most x.swift ├── 2810. Faulty Keyboard.swift ├── 2811. Check if it is Possible to Split Array.swift ├── 2812. Find the Safest Path in a Grid.swift ├── 2813. Maximum Elegance of a K-Length Subsequence.swift ├── 2815. Max Pair Sum in an Array.swift ├── 2816. Double a Number Represented as a Linked List.swift ├── 2818. Apply Operations to Maximize Score.swift ├── 2824. Count Pairs Whose Sum is Less than Target.swift ├── 2825. Make String a Subsequence Using Cyclic Increments.swift ├── 2826. Sorting Three Groups.swift ├── 2827. Number of Beautiful Integers in the Range.swift ├── 2828. Check if a String Is an Acronym of Words.swift ├── 2829. Determine the Minimum Sum of a k-avoiding Array.swift ├── 2830. Maximize the Profit as the Salesman.swift ├── 2831. Find the Longest Equal Subarray.swift ├── 2833. Furthest Point From Origin.swift ├── 2835. Minimum Operations to Form Subsequence With Target Sum.swift ├── 2836. Maximize Value of Function in a Ball Passing Game.swift ├── 2839. Check if Strings Can be Made Equal With Operations I.swift ├── 2840. Check if Strings Can be Made Equal With Operations II.swift ├── 2841. Maximum Sum of Almost Unique Subarray.swift ├── 2842. Count K-Subsequences of a String With Maximum Beauty.swift ├── 2843. Count Symmetric Integers.swift ├── 2844. Minimum Operations to Make a Special Number.swift ├── 2845. Count of Interesting Subarrays.swift ├── 2846. Minimum Edge Weight Equilibrium Queries in a Tree.swift ├── 2848. Points That Intersect With Cars.swift ├── 2849. Determine if a Cell Is Reachable at a Given Time.swift ├── 2850. Minimum Moves to Spread Stones Over Grid.swift ├── 2855. Minimum Right Shifts to Sort the Array.swift ├── 2856. Minimum Array Length After Pair Removals.swift ├── 2857. Count Pairs of Points With Distance k.swift ├── 2858. Minimum Edge Reversals So Every Node Is Reachable.swift ├── 2859. Sum of Values at Indices With K Set Bits.swift ├── 2860. Happy Students.swift ├── 2861. Maximum Number of Alloys.swift ├── 2862. Maximum Element-Sum of a Complete Subset of Indices.swift ├── 2864. Maximum Odd Binary Number.swift ├── 2865. Beautiful Towers I.swift ├── 2866. Beautiful Towers II.swift ├── 2867. Count Valid Paths in a Tree.swift ├── 2869. Minimum Operations to Collect Elements.swift ├── 2870. Minimum Number of Operations to Make Array Empty.swift ├── 2871. Split Array Into Maximum Number of Subarrays.swift ├── 2872. Maximum Number of K-Divisible Components.swift ├── 2873. Maximum Value of an Ordered Triplet I.swift ├── 2874. Maximum Value of an Ordered Triplet II.swift ├── 2875. Minimum Size Subarray in Infinite Array.swift ├── 2876. Count Visited Nodes in a Directed Graph.swift ├── 2894. Divisible and Non-divisible Sums Difference.swift ├── 2895. Minimum Processing Time.swift ├── 2896. Apply Operations to Make Two Strings Equal.swift ├── 2897. Apply Operations on Array to Maximize Sum of Squares.swift ├── 2899. Last Visited Integers.swift ├── 2900. Longest Unequal Adjacent Groups Subsequence I.swift ├── 2901. Longest Unequal Adjacent Groups Subsequence II.swift ├── 2902. Count of Sub-Multisets With Bounded Sum.swift ├── 2903. Find Indices With Index and Value Difference I.swift ├── 2904. Shortest and Lexicographically Smallest Beautiful String.swift ├── 2905. Find Indices With Index and Value Difference II.swift ├── 2906. Construct Product Matrix.swift ├── 2908. Minimum Sum of Mountain Triplets I.swift ├── 2909. Minimum Sum of Mountain Triplets II.swift ├── 2910. Minimum Number of Groups to Create a Valid Assignment.swift ├── 2913. Subarrays Distinct Element Sum of Squares I.swift ├── 2914. Minimum Number of Changes to Make Binary String Beautiful.swift ├── 2915. Length of the Longest Subsequence That Sums to Target.swift ├── 2916. Subarrays Distinct Element Sum of Squares II.swift ├── 2917. Find the K-or of an Array.swift ├── 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros.swift ├── 2919. Minimum Increment Operations to Make Array Beautiful.swift ├── 2920. Maximum Points After Collecting Coins From All Nodes.swift ├── 2923. Find Champion I.swift ├── 2924. Find Champion II.swift ├── 2925. Maximum Score After Applying Operations on a Tree.swift ├── 2926. Maximum Balanced Subsequence Sum.swift ├── 2928. Distribute Candies Among Children I.swift ├── 2929. Distribute Candies Among Children II.swift ├── 2930. Number of Strings Which Can Be Rearranged to Contain Substring.swift ├── 2931. Maximum Spending After Buying Items.swift ├── 2932. Maximum Strong Pair XOR I.swift ├── 2933. High-Access Employees.swift ├── 2934. Minimum Operations to Maximize Last Elements in Arrays.swift ├── 2935. Maximum Strong Pair XOR II.swift ├── 2937. Make Three Strings Equal.swift ├── 2938. Separate Black and White Balls.swift ├── 2939. Maximum Xor Product.swift ├── 2940. Find Building Where Alice and Bob Can Meet.swift ├── 2942. Find Words Containing Character.swift ├── 2943. Maximize Area of Square Hole in Grid.swift ├── 2944. Minimum Number of Coins for Fruits.swift ├── 2945. Find Maximum Non-decreasing Array Length.swift ├── 2946. Matrix Similarity After Cyclic Shifts.swift ├── 2947. Count Beautiful Substrings I.swift ├── 2948. Make Lexicographically Smallest Array by Swapping Elements.swift ├── 2949. Count Beautiful Substrings II.swift ├── 2951. Find the Peaks.swift ├── 2952. Minimum Number of Coins to be Added.swift ├── 2954. Count the Number of Infection Sequences.swift ├── 2956. Find Common Elements Between Two Arrays.swift ├── 2957. Remove Adjacent Almost-Equal Characters.swift ├── 2958. Length of Longest Subarray With at Most K Frequency.swift ├── 2959. Number of Possible Sets of Closing Branches.swift ├── 2960. Count Tested Devices After Test Operations.swift ├── 2961. Double Modular Exponentiation.swift ├── 2962. Count Subarrays Where Max Element Appears at Least K Times.swift ├── 2963. Count the Number of Good Partitions.swift ├── 2965. Find Missing and Repeated Values.swift ├── 2966. Divide Array Into Arrays With Max Difference.swift ├── 2967. Minimum Cost to Make Array Equalindromic.swift ├── 2968. Apply Operations to Maximize Frequency Score.swift ├── 2970. Count the Number of Incremovable Subarrays I.swift ├── 2971. Find Polygon With the Largest Perimeter.swift ├── 2972. Count the Number of Incremovable Subarrays II.swift ├── 2973. Find Number of Coins to Place in Tree Nodes.swift ├── 2974. Minimum Number Game.swift ├── 2975. Maximum Square Area by Removing Fences From a Field.swift ├── 2976. Minimum Cost to Convert String I.swift ├── 2980. Check if Bitwise OR Has Trailing Zeros.swift ├── 2981. Find Longest Special Substring That Occurs Thrice I.swift ├── 2982. Find Longest Special Substring That Occurs Thrice II.swift └── 2996. Smallest Missing Integer Greater Than Sequential Prefix Sum.swift ├── LICENSE └── README.md /.swift-format: -------------------------------------------------------------------------------- 1 | { 2 | "indentation" : { 3 | "spaces" : 4 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /0001-0500/0096. Unique Binary Search Trees.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 96. Unique Binary Search Trees 6 | // Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. 7 | 8 | // Example 1: 9 | // Input: n = 3 10 | // Output: 5 11 | 12 | // Example 2: 13 | // Input: n = 1 14 | // Output: 1 15 | 16 | // Constraints: 17 | // 1 <= n <= 19 18 | 19 | func numTrees(_ n: Int) -> Int { 20 | guard n > 1 else { return 1 } 21 | 22 | var map: [Int] = [1, 1] 23 | 24 | for i in 2...n { 25 | var tmp = 0 26 | 27 | for j in 0.. Int { 27 | var num = n 28 | var count = 0 29 | 30 | while num > 0 { 31 | count += num / 5 32 | num /= 5 33 | } 34 | 35 | return count 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /0001-0500/0176. Second Highest Salary.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 176. Second Highest Salary 3 | -- Write a SQL query to get the second highest salary from the Employee table. 4 | -- +----+--------+ 5 | -- | Id | Salary | 6 | -- +----+--------+ 7 | -- | 1 | 100 | 8 | -- | 2 | 200 | 9 | -- | 3 | 300 | 10 | -- +----+--------+ 11 | -- For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null. 12 | -- +---------------------+ 13 | -- | SecondHighestSalary | 14 | -- +---------------------+ 15 | -- | 200 | 16 | -- +---------------------+ 17 | -- MySQL query statement below 18 | select 19 | max(Salary) as SecondHighestSalary 20 | from 21 | Employee 22 | where 23 | Salary < ( 24 | select 25 | max(Salary) 26 | from 27 | Employee 28 | ) -------------------------------------------------------------------------------- /0001-0500/0177. Nth Highest Salary.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 177. Nth Highest Salary 3 | -- Write a SQL query to get the nth highest salary from the Employee table. 4 | -- +----+--------+ 5 | -- | Id | Salary | 6 | -- +----+--------+ 7 | -- | 1 | 100 | 8 | -- | 2 | 200 | 9 | -- | 3 | 300 | 10 | -- +----+--------+ 11 | -- For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null. 12 | -- +------------------------+ 13 | -- | getNthHighestSalary(2) | 14 | -- +------------------------+ 15 | -- | 200 | 16 | -- +------------------------+ 17 | create function getNthHighestSalary(N int) returns int begin declare M int; 18 | 19 | set 20 | M = N -1; 21 | 22 | return ( 23 | # MySQL query statement below. 24 | select 25 | distinct Salary 26 | from 27 | Employee 28 | order by 29 | Salary desc 30 | limit 31 | M, 1 32 | ); 33 | 34 | end -------------------------------------------------------------------------------- /0001-0500/0181. Employees Earning More Than Their Managers.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 181. Employees Earning More Than Their Managers 3 | -- The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id. 4 | -- +----+-------+--------+-----------+ 5 | -- | Id | Name | Salary | ManagerId | 6 | -- +----+-------+--------+-----------+ 7 | -- | 1 | Joe | 70000 | 3 | 8 | -- | 2 | Henry | 80000 | 4 | 9 | -- | 3 | Sam | 60000 | NULL | 10 | -- | 4 | Max | 90000 | NULL | 11 | -- +----+-------+--------+-----------+ 12 | -- Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager. 13 | -- +----------+ 14 | -- | Employee | 15 | -- +----------+ 16 | -- | Joe | 17 | -- +----------+ 18 | -- MySQL query statement below 19 | select 20 | E1.Name as Employee 21 | from 22 | Employee as E1, 23 | Employee as E2 24 | where 25 | E1.ManagerId = E2.Id 26 | and E1.Salary > E2.Salary -------------------------------------------------------------------------------- /0001-0500/0182. Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 182. Duplicate Emails 3 | -- Write a SQL query to find all duplicate emails in a table named Person. 4 | -- +----+---------+ 5 | -- | Id | Email | 6 | -- +----+---------+ 7 | -- | 1 | a@b.com | 8 | -- | 2 | c@d.com | 9 | -- | 3 | a@b.com | 10 | -- +----+---------+ 11 | -- For example, your query should return the following for the above table: 12 | -- +---------+ 13 | -- | Email | 14 | -- +---------+ 15 | -- | a@b.com | 16 | -- +---------+ 17 | -- Note: All emails are in lowercase. 18 | -- MySQL query statement below 19 | select 20 | distinct one.Email 21 | from 22 | Person one, 23 | Person two 24 | where 25 | one.Id <> two.Id 26 | and one.Email = two.Email; -------------------------------------------------------------------------------- /0001-0500/0183. Customers Who Never Order.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 183. Customers Who Never Order 3 | -- Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything. 4 | -- Table: Customers. 5 | -- +----+-------+ 6 | -- | Id | Name | 7 | -- +----+-------+ 8 | -- | 1 | Joe | 9 | -- | 2 | Henry | 10 | -- | 3 | Sam | 11 | -- | 4 | Max | 12 | -- +----+-------+ 13 | -- Table: Orders. 14 | -- +----+------------+ 15 | -- | Id | CustomerId | 16 | -- +----+------------+ 17 | -- | 1 | 3 | 18 | -- | 2 | 1 | 19 | -- +----+------------+ 20 | -- Using the above tables as example, return the following: 21 | -- +-----------+ 22 | -- | Customers | 23 | -- +-----------+ 24 | -- | Henry | 25 | -- | Max | 26 | -- +-----------+ 27 | -- MySQL query statement below 28 | select 29 | Name as Customers 30 | from 31 | Customers 32 | where 33 | Id not in ( 34 | select 35 | distinct CustomerId 36 | from 37 | Orders 38 | ); -------------------------------------------------------------------------------- /0001-0500/0192. Word Frequency.sh: -------------------------------------------------------------------------------- 1 | # Solution by Sergey Leschev 2 | 3 | # 192. Word Frequency 4 | # Write a bash script to calculate the frequency of each word in a text file words.txt. 5 | 6 | # For simplicity sake, you may assume: 7 | # words.txt contains only lowercase characters and space ' ' characters. 8 | # Each word must consist of lowercase characters only. 9 | # Words are separated by one or more whitespace characters. 10 | # Example: 11 | 12 | # Assume that words.txt has the following content: 13 | # the day is sunny the the 14 | # the sunny is is 15 | # Your script should output the following, sorted by descending frequency: 16 | # the 4 17 | # is 3 18 | # sunny 2 19 | # day 1 20 | # Note: 21 | # Don't worry about handling ties, it is guaranteed that each word's frequency count is unique. 22 | # Could you write it in one-line using Unix pipes? 23 | 24 | # Read from the file words.txt and output the word frequency list to stdout. 25 | 26 | cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2, $1}' 27 | -------------------------------------------------------------------------------- /0001-0500/0193. Valid Phone Numbers.sh: -------------------------------------------------------------------------------- 1 | # Solution by Sergey Leschev 2 | 3 | # 193. Valid Phone Numbers 4 | # Given a text file file.txt that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers. 5 | # You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) 6 | # You may also assume each line in the text file must not contain leading or trailing white spaces. 7 | 8 | # Example: 9 | # Assume that file.txt has the following content: 10 | 11 | # 987-123-4567 12 | # 123 456 7890 13 | # (123) 456-7890 14 | # Your script should output the following valid phone numbers: 15 | # 987-123-4567 16 | # (123) 456-7890 17 | 18 | # Read from the file file.txt and output all valid phone numbers to stdout. 19 | 20 | grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt 21 | -------------------------------------------------------------------------------- /0001-0500/0194. Transpose File.sh: -------------------------------------------------------------------------------- 1 | # Solution by Sergey Leschev 2 | 3 | # 194. Transpose File 4 | # Given a text file file.txt, transpose its content. 5 | # You may assume that each row has the same number of columns, and each field is separated by the ' ' character. 6 | 7 | # Example: 8 | # If file.txt has the following content: 9 | # name age 10 | # alice 21 11 | # ryan 30 12 | # Output the following: 13 | # name alice ryan 14 | # age 21 30 15 | 16 | # Read from the file file.txt and print its transposed content to stdout. 17 | 18 | awk ' 19 | { 20 | for (i = 1; i <= NF; i++) { 21 | if(NR == 1) { 22 | s[i] = $i; 23 | } else { 24 | s[i] = s[i] " " $i; 25 | } 26 | } 27 | } 28 | END { 29 | for (i = 1; s[i] != ""; i++) { 30 | print s[i]; 31 | } 32 | }' file.txt 33 | -------------------------------------------------------------------------------- /0001-0500/0195. Tenth Line.sh: -------------------------------------------------------------------------------- 1 | # Solution by Sergey Leschev 2 | 3 | # 195. Tenth Line 4 | # Given a text file file.txt, print just the 10th line of the file. 5 | 6 | # Example: 7 | # Assume that file.txt has the following content: 8 | # Line 1 9 | # Line 2 10 | # Line 3 11 | # Line 4 12 | # Line 5 13 | # Line 6 14 | # Line 7 15 | # Line 8 16 | # Line 9 17 | # Line 10 18 | # Your script should output the tenth line, which is: 19 | # Line 10 20 | # Note: 21 | # 1. If the file contains less than 10 lines, what should you output? 22 | # 2. There's at least three different solutions. Try to explore all possibilities. 23 | 24 | # Read from the file file.txt and output the tenth line to stdout. 25 | 26 | sed -n 10p file.txt 27 | -------------------------------------------------------------------------------- /0001-0500/0196. Delete Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 196. Delete Duplicate Emails 3 | -- Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id. 4 | -- +----+------------------+ 5 | -- | Id | Email | 6 | -- +----+------------------+ 7 | -- | 1 | john@example.com | 8 | -- | 2 | bob@example.com | 9 | -- | 3 | john@example.com | 10 | -- +----+------------------+ 11 | -- Id is the primary key column for this table. 12 | -- For example, after running your query, the above Person table should have the following rows: 13 | -- +----+------------------+ 14 | -- | Id | Email | 15 | -- +----+------------------+ 16 | -- | 1 | john@example.com | 17 | -- | 2 | bob@example.com | 18 | -- +----+------------------+ 19 | -- Note: 20 | -- Your output is the whole Person table after executing your sql. Use delete statement. 21 | -- MySQL query statement below 22 | delete P1 23 | from 24 | Person p1 25 | join Person p2 on p1.Email = p2.Email 26 | and p1.ID > p2.ID -------------------------------------------------------------------------------- /0001-0500/0201. Bitwise AND of Numbers Range.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 201. Bitwise AND of Numbers Range 6 | // Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive. 7 | 8 | // Example 1: 9 | // Input: left = 5, right = 7 10 | // Output: 4 11 | 12 | // Example 2: 13 | // Input: left = 0, right = 0 14 | // Output: 0 15 | 16 | // Example 3: 17 | // Input: left = 1, right = 2147483647 18 | // Output: 0 19 | 20 | // Constraints: 21 | // 0 <= left <= right <= 2^31 - 1 22 | 23 | func rangeBitwiseAnd(_ left: Int, _ right: Int) -> Int { 24 | var mask = 0 25 | 26 | for i in 0..<32 { 27 | let temp = 1 << (31 - i) 28 | if temp & left == temp & right { 29 | mask |= temp 30 | } else { 31 | break 32 | } 33 | } 34 | 35 | return right & mask 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /0001-0500/0326. Power of Three.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 326. Power of Three 6 | // Given an integer n, return true if it is a power of three. Otherwise, return false. 7 | // An integer n is a power of three, if there exists an integer x such that n == 3x. 8 | 9 | // Example 1: 10 | // Input: n = 27 11 | // Output: true 12 | 13 | // Example 2: 14 | // Input: n = 0 15 | // Output: false 16 | 17 | // Example 3: 18 | // Input: n = 9 19 | // Output: true 20 | 21 | // Example 4: 22 | // Input: n = 45 23 | // Output: false 24 | 25 | // Constraints: 26 | // -2^31 <= n <= 2^31 - 1 27 | 28 | // Follow up: Could you solve it without loops/recursion? 29 | 30 | func isPowerOfThree(_ n: Int) -> Bool { n > 0 && (1_162_261_467 % n == 0) } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /0001-0500/0343. Integer Break.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 343. Integer Break 6 | // Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers. 7 | // Return the maximum product you can get. 8 | 9 | // Example 1: 10 | // Input: n = 2 11 | // Output: 1 12 | // Explanation: 2 = 1 + 1, 1 × 1 = 1. 13 | 14 | // Example 2: 15 | // Input: n = 10 16 | // Output: 36 17 | // Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36. 18 | 19 | // Constraints: 20 | // 2 <= n <= 58 21 | 22 | func integerBreak(_ n: Int) -> Int { 23 | if n == 2 { return 1 } 24 | if n == 3 { return 2 } 25 | 26 | var num = n 27 | var res = 1 28 | 29 | while num > 4 { 30 | res *= 3 31 | num -= 3 32 | } 33 | 34 | return num > 0 ? res * num : res 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /0001-0500/0357. Count Numbers with Unique Digits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 357. Count Numbers with Unique Digits 6 | // Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. 7 | 8 | // Example 1: 9 | // Input: n = 2 10 | // Output: 91 11 | // Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 12 | 13 | // Example 2: 14 | // Input: n = 0 15 | // Output: 1 16 | 17 | // Constraints: 18 | // 0 <= n <= 8 19 | 20 | func countNumbersWithUniqueDigits(_ n: Int) -> Int { 21 | var result = 0 22 | 23 | if n == 1 { return 10 } else if n == 0 { return 1 } 24 | 25 | for i in 2...n { 26 | var temp = 1 27 | for j in 2...i { temp *= 9 - j + 2 } 28 | result += temp * 9 29 | } 30 | 31 | return result + 10 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /0001-0500/0371. Sum of Two Integers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 371. Sum of Two Integers 6 | // Given two integers a and b, return the sum of the two integers without using the operators + and -. 7 | 8 | // Example 1: 9 | // Input: a = 1, b = 2 10 | // Output: 3 11 | 12 | // Example 2: 13 | // Input: a = 2, b = 3 14 | // Output: 5 15 | 16 | // Constraints: 17 | // -1000 <= a, b <= 1000 18 | 19 | func getSum(_ a: Int, _ b: Int) -> Int { 20 | var c = a 21 | var d = b 22 | 23 | while d != 0 { 24 | let sum = c ^ d 25 | let carry = (c & d) << 1 26 | c = sum 27 | d = carry 28 | } 29 | 30 | return c 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /0001-0500/0386. Lexicographical Numbers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 386. Lexicographical Numbers 6 | // Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order. 7 | // You must write an algorithm that runs in O(n) time and uses O(1) extra space. 8 | 9 | // Example 1: 10 | // Input: n = 13 11 | // Output: [1,10,11,12,13,2,3,4,5,6,7,8,9] 12 | 13 | // Example 2: 14 | // Input: n = 2 15 | // Output: [1,2] 16 | 17 | // Constraints: 18 | // 1 <= n <= 5 * 10^4 19 | 20 | func lexicalOrder(_ n: Int) -> [Int] { 21 | var ans = [Int]() 22 | 23 | func innerLexicalOrder(current: Int) { 24 | ans.append(current) 25 | for i in 0...9 { 26 | let next = current * 10 + i 27 | guard next <= n else { return } 28 | innerLexicalOrder(current: next) 29 | } 30 | } 31 | 32 | for i in 1...9 where i <= n { innerLexicalOrder(current: i) } 33 | return ans 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /0001-0500/0479. Largest Palindrome Product.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 479. Largest Palindrome Product 6 | // Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337. 7 | 8 | // Example 1: 9 | // Input: n = 2 10 | // Output: 987 11 | // Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 12 | 13 | // Example 2: 14 | // Input: n = 1 15 | // Output: 9 16 | 17 | // Constraints: 18 | // 1 <= n <= 8 19 | 20 | func largestPalindrome(_ n: Int) -> Int { 21 | [ 22 | 9, 9009, 906609, 99_000_099, 9_966_006_699, 999_000_000_999, 23 | 99_956_644_665_999, 9_999_000_000_009_999, 24 | ][n - 1] % 1337 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /0501-1000/0504. Base 7.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 504. Base 7 6 | // Given an integer num, return a string of its base 7 representation. 7 | 8 | // Example 1: 9 | // Input: num = 100 10 | // Output: "202" 11 | 12 | // Example 2: 13 | // Input: num = -7 14 | // Output: "-10" 15 | 16 | // Constraints: 17 | // -10^7 <= num <= 10^7 18 | 19 | func convertToBase7(_ num: Int) -> String { 20 | if num == 0 { return "0" } 21 | var result = "" 22 | var n = abs(num) 23 | 24 | while n > 0 { 25 | let remainder = n % 7 26 | result = "\(remainder)" + result 27 | n /= 7 28 | } 29 | 30 | return num < 0 ? "-" + result : result 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /0501-1000/0509. Fibonacci Number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 509. Fibonacci Number 6 | // The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 7 | // F(0) = 0, F(1) = 1 8 | // F(n) = F(n - 1) + F(n - 2), for n > 1. 9 | // Given n, calculate F(n). 10 | 11 | // Example 1: 12 | // Input: n = 2 13 | // Output: 1 14 | // Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 15 | 16 | // Example 2: 17 | // Input: n = 3 18 | // Output: 2 19 | // Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 20 | 21 | // Example 3: 22 | // Input: n = 4 23 | // Output: 3 24 | // Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 25 | 26 | // Constraints: 27 | // 0 <= n <= 30 28 | 29 | func fib(_ n: Int) -> Int { 30 | if n == 0 { return 0 } 31 | if n == 1 { return 1 } 32 | 33 | return fib(n - 1) + fib(n - 2) 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /0501-1000/0550. Game Play Analysis IV.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 0550. Game Play Analysis IV 3 | -- MySQL 4 | SELECT 5 | ROUND(COUNT(t2.player_id) / COUNT(t1.player_id), 2) AS fraction 6 | FROM 7 | ( 8 | SELECT 9 | player_id, 10 | MIN(event_date) AS first_login 11 | FROM 12 | Activity 13 | GROUP BY 14 | player_id 15 | ) t1 16 | LEFT JOIN Activity t2 ON t1.player_id = t2.player_id 17 | AND t1.first_login = t2.event_date - INTERVAL 1 DAY; -------------------------------------------------------------------------------- /0501-1000/0560. Subarray Sum Equals K.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 560. Subarray Sum Equals K 6 | // Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k. 7 | 8 | // Example 1: 9 | // Input: nums = [1,1,1], k = 2 10 | // Output: 2 11 | 12 | // Example 2: 13 | // Input: nums = [1,2,3], k = 3 14 | // Output: 2 15 | 16 | // Constraints: 17 | // 1 <= nums.length <= 2 * 10^4 18 | // -1000 <= nums[i] <= 1000 19 | // -10^7 <= k <= 10^7 20 | 21 | // Use hash map to record the number of prefix sum's appearance. 22 | 23 | func subarraySum(_ nums: [Int], _ k: Int) -> Int { 24 | var prefixSum = 0 25 | var map = [0: 1] 26 | var count = 0 27 | 28 | for i in 0..= 5 18 | OR e.managerId IS NULL; -------------------------------------------------------------------------------- /0501-1000/0577. Employee Bonus.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | name, 5 | bonus 6 | FROM 7 | Employee e 8 | LEFT JOIN Bonus b ON e.empId = b.empId 9 | WHERE 10 | bonus < 1000 11 | OR bonus IS NULL; -------------------------------------------------------------------------------- /0501-1000/0585. Investments in 2016.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | ROUND(SUM(tiv_2016), 2) AS tiv_2016 5 | FROM 6 | Insurance 7 | WHERE 8 | tiv_2015 IN ( 9 | SELECT 10 | tiv_2015 11 | FROM 12 | Insurance 13 | GROUP BY 14 | tiv_2015 15 | HAVING 16 | COUNT(*) > 1 17 | ) 18 | AND (lat, lon) IN ( 19 | SELECT 20 | lat, 21 | lon 22 | FROM 23 | Insurance 24 | GROUP BY 25 | lat, 26 | lon 27 | HAVING 28 | COUNT(*) = 1 29 | ); -------------------------------------------------------------------------------- /0501-1000/0596. Classes More Than 5 Students.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 596. Classes More Than 5 Students 3 | -- There is a table courses with columns: student and class 4 | -- Please list out all classes which have more than or equal to 5 students. 5 | -- For example, the table: 6 | -- +---------+------------+ 7 | -- | student | class | 8 | -- +---------+------------+ 9 | -- | A | Math | 10 | -- | B | English | 11 | -- | C | Math | 12 | -- | D | Biology | 13 | -- | E | Math | 14 | -- | F | Computer | 15 | -- | G | Math | 16 | -- | H | Math | 17 | -- | I | Math | 18 | -- +---------+------------+ 19 | -- Should output: 20 | -- +---------+ 21 | -- | class | 22 | -- +---------+ 23 | -- | Math | 24 | -- +---------+ 25 | -- Note: 26 | -- The students should not be counted duplicate in each course. 27 | -- MySQL query statement below 28 | select 29 | class 30 | from 31 | courses 32 | group by 33 | class 34 | having 35 | count(distinct student) >= 5 -------------------------------------------------------------------------------- /0501-1000/0602. Friend Requests II Who Has the Most Friends.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | id, 5 | COUNT(*) as num 6 | FROM 7 | ( 8 | SELECT 9 | requester_id AS id 10 | FROM 11 | RequestAccepted 12 | UNION 13 | ALL 14 | SELECT 15 | accepter_id AS id 16 | FROM 17 | RequestAccepted 18 | ) AS friends 19 | GROUP BY 20 | id 21 | ORDER BY 22 | num DESC 23 | LIMIT 24 | 1; -------------------------------------------------------------------------------- /0501-1000/0610. Triangle Judgement.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | x, 5 | y, 6 | z, 7 | CASE 8 | WHEN x + y > z 9 | AND x + z > y 10 | AND y + z > x THEN 'Yes' 11 | ELSE 'No' 12 | END AS triangle 13 | FROM 14 | Triangle; -------------------------------------------------------------------------------- /0501-1000/0619. Biggest Single Number.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | MAX(num) AS num 5 | FROM 6 | ( 7 | SELECT 8 | num 9 | FROM 10 | MyNumbers 11 | GROUP BY 12 | num 13 | HAVING 14 | COUNT(*) = 1 15 | ) AS single_numbers; -------------------------------------------------------------------------------- /0501-1000/0628. Maximum Product of Three Numbers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 628. Maximum Product of Three Numbers 6 | // Given an integer array nums, find three numbers whose product is maximum and return the maximum product. 7 | 8 | // Example 1: 9 | // Input: nums = [1,2,3] 10 | // Output: 6 11 | 12 | // Example 2: 13 | // Input: nums = [1,2,3,4] 14 | // Output: 24 15 | 16 | // Example 3: 17 | // Input: nums = [-1,-2,-3] 18 | // Output: -6 19 | 20 | // Constraints: 21 | // 3 <= nums.length <= 10^4 22 | // -1000 <= nums[i] <= 1000 23 | 24 | func maximumProduct(_ nums: [Int]) -> Int { 25 | var nums = nums.sorted(by: >) 26 | 27 | return max( 28 | nums[0] * nums[1] * nums[2], nums[0] * nums[nums.count - 1] * nums[nums.count - 2]) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /0501-1000/0796. Rotate String.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 796. Rotate String 6 | // We are given two strings, s and goal. 7 | // A shift on s consists of taking string s and moving the leftmost character to the rightmost position. For example, if s = 'abcde', then it will be 'bcdea' after one shift on s. Return true if and only if s can become goal after some number of shifts on s. 8 | 9 | // Example 1: 10 | // Input: s = 'abcde', goal = 'cdeab' 11 | // Output: true 12 | 13 | // Example 2: 14 | // Input: s = 'abcde', goal = 'abced' 15 | // Output: false 16 | // Note: 17 | // s and goal will have length at most 100. 18 | 19 | func rotateString(_ A: String, _ B: String) -> Bool { 20 | (A.count == B.count && (B + B).contains(A)) || (A.count == 0 && B.count == 0) 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /0501-1000/0961. N-Repeated Element in Size 2N Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 961. N-Repeated Element in Size 2N Array 6 | // In a array nums of size 2 * n, there are n + 1 unique elements, and exactly one of these elements is repeated n times. 7 | // Return the element repeated n times. 8 | 9 | // Example 1: 10 | // Input: nums[1,2,3,3] 11 | // Output: 3 12 | 13 | // Example 2: 14 | // Input: nums[2,1,2,5,3,2] 15 | // Output: 2 16 | 17 | // Example 3: 18 | // Input: nums[5,1,5,2,5,3,5,4] 19 | // Output: 5 20 | 21 | // Note: 22 | // 4 <= nums.length <= 10000 23 | // 0 <= nums[i] < 10000 24 | // nums.length is even 25 | 26 | // - Complexity: 27 | // - time: O(n) 28 | // - space: O(n) 29 | 30 | func repeatedNTimes(_ A: [Int]) -> Int { 31 | let map = A.reduce(into: [:]) { dict, num in dict[num, default: 0] += 1 } 32 | 33 | for num in A { 34 | if let count = map[num], count > 1 { return num } 35 | } 36 | 37 | return -1 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /1001-1500/1017. Convert to Base -2.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1017. Convert to Base -2 6 | // Given a number n, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two). 7 | // The returned string must have no leading zeroes, unless the string is "0". 8 | 9 | // Example 1: 10 | // Input: n = 2 11 | // Output: "110" 12 | // Explanation: (-2) ^ 2 + (-2) ^ 1 = 2 13 | 14 | // Example 2: 15 | // Input: n = 3 16 | // Output: "111" 17 | // Explanation: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3 18 | 19 | // Example 3: 20 | // Input: n = 4 21 | // Output: "100" 22 | // Explanation: (-2) ^ 2 = 4 23 | 24 | // Note: 25 | // 0 <= n <= 10^9 26 | 27 | func baseNeg2(_ N: Int) -> String { 28 | if N == 0 { return "0" } 29 | var N = N 30 | var ans = String() 31 | 32 | while N != 0 { 33 | ans = String(N & 1) + ans 34 | N = -(N >> 1) 35 | } 36 | 37 | return ans 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /1001-1500/1025. Divisor Game.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1025. Divisor Game 6 | // Alice and Bob take turns playing a game, with Alice starting first. 7 | // Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: 8 | // Choosing any x with 0 < x < n and n % x == 0. 9 | // Replacing the number n on the chalkboard with n - x. 10 | // Also, if a player cannot make a move, they lose the game. 11 | // Return true if and only if Alice wins the game, assuming both players play optimally. 12 | 13 | // Example 1: 14 | // Input: n = 2 15 | // Output: true 16 | // Explanation: Alice chooses 1, and Bob has no more moves. 17 | 18 | // Example 2: 19 | // Input: n = 3 20 | // Output: false 21 | // Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves. 22 | 23 | // Constraints: 24 | // 1 <= n <= 1000 25 | 26 | func divisorGame(_ N: Int) -> Bool { N % 2 == 0 } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /1001-1500/1045. Customers Who Bought All Products.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | customer_id 5 | FROM 6 | Customer 7 | GROUP BY 8 | customer_id 9 | HAVING 10 | COUNT(DISTINCT product_key) = ( 11 | SELECT 12 | COUNT(*) 13 | FROM 14 | Product 15 | ) -------------------------------------------------------------------------------- /1001-1500/1068. Product Sales Analysis I.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | p.product_name, 5 | s.year, 6 | s.price 7 | FROM 8 | Sales s 9 | JOIN Product p ON s.product_id = p.product_id -------------------------------------------------------------------------------- /1001-1500/1070. Product Sales Analysis III.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | WITH min_sales AS ( 4 | SELECT 5 | product_id, 6 | MIN(year) AS min_year 7 | FROM 8 | Sales 9 | GROUP BY 10 | product_id 11 | ) 12 | SELECT 13 | s.product_id, 14 | s.year AS first_year, 15 | s.quantity, 16 | s.price 17 | FROM 18 | Sales s 19 | JOIN Product p ON s.product_id = p.product_id 20 | JOIN min_sales ms ON s.product_id = ms.product_id 21 | AND s.year = ms.min_year; -------------------------------------------------------------------------------- /1001-1500/1075. Project Employees I.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | project_id, 5 | ROUND(AVG(experience_years), 2) AS average_years 6 | FROM 7 | Project 8 | JOIN Employee ON Project.employee_id = Employee.employee_id 9 | GROUP BY 10 | project_id; -------------------------------------------------------------------------------- /1001-1500/1108. Defanging an IP Address.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1108. Defanging an IP Address 6 | // Given a valid (IPv4) IP address, return a defanged version of that IP address. 7 | // A defanged IP address replaces every period "." with "[.]". 8 | 9 | // Example 1: 10 | // Input: address = "1.1.1.1" 11 | // Output: "1[.]1[.]1[.]1" 12 | 13 | // Example 2: 14 | // Input: address = "255.100.50.0" 15 | // Output: "255[.]100[.]50[.]0" 16 | 17 | // Constraints: 18 | // The given address is a valid IPv4 address. 19 | 20 | func defangIPaddr(_ address: String) -> String { 21 | address.replacingOccurrences(of: ".", with: "[.]") 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /1001-1500/1163. Last Substring in Lexicographical Order.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1163. Last Substring in Lexicographical Order 6 | // Given a string s, return the last substring of s in lexicographical order. 7 | 8 | // Example 1: 9 | // Input: s = "abab" 10 | // Output: "bab" 11 | // Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab". 12 | 13 | // Example 2: 14 | // Input: s = "leetcode" 15 | // Output: "tcode" 16 | 17 | // Constraints: 18 | // 1 <= s.length <= 4 * 10^5 19 | // s contains only lowercase English letters. 20 | 21 | func lastSubstring(_ s: String) -> String { 22 | var max = "" 23 | 24 | for index in s.indices { 25 | let suffix = s[index.. max { max = String(suffix) } 27 | } 28 | 29 | return max 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /1001-1500/1164. Product Price at a Given Date.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 1164. Product Price at a Given Date 3 | -- MySQL 4 | SELECT 5 | product_id, 6 | COALESCE(new_price, 10) AS price 7 | FROM 8 | ( 9 | SELECT 10 | product_id, 11 | new_price, 12 | change_date, 13 | ROW_NUMBER() OVER ( 14 | PARTITION BY product_id 15 | ORDER BY 16 | change_date DESC 17 | ) AS rn 18 | FROM 19 | Products 20 | WHERE 21 | change_date <= '2019-08-16' 22 | ) AS subquery 23 | WHERE 24 | rn = 1 25 | UNION 26 | SELECT 27 | DISTINCT product_id, 28 | 10 AS price 29 | FROM 30 | Products 31 | WHERE 32 | product_id NOT IN ( 33 | SELECT 34 | DISTINCT product_id 35 | FROM 36 | Products 37 | WHERE 38 | change_date <= '2019-08-16' 39 | ); -------------------------------------------------------------------------------- /1001-1500/1174. Immediate Food Delivery II.sql: -------------------------------------------------------------------------------- 1 | -- Solution by Sergey Leschev 2 | -- 1174. Immediate Food Delivery II 3 | -- MySQL query 4 | select 5 | round( 6 | avg(order_date = customer_pref_delivery_date) * 100, 7 | 2 8 | ) as immediate_percentage 9 | from 10 | Delivery 11 | where 12 | (customer_id, order_date) in ( 13 | select 14 | customer_id, 15 | min(order_date) 16 | from 17 | Delivery 18 | group by 19 | customer_id 20 | ); -------------------------------------------------------------------------------- /1001-1500/1193. Monthly Transactions I.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | DATE_FORMAT(trans_date, '%Y-%m') AS month, 5 | country, 6 | COUNT(*) AS trans_count, 7 | SUM( 8 | CASE 9 | WHEN state = 'approved' THEN 1 10 | ELSE 0 11 | END 12 | ) AS approved_count, 13 | SUM(amount) AS trans_total_amount, 14 | SUM( 15 | CASE 16 | WHEN state = 'approved' THEN amount 17 | ELSE 0 18 | END 19 | ) AS approved_total_amount 20 | FROM 21 | Transactions 22 | GROUP BY 23 | month, 24 | country; -------------------------------------------------------------------------------- /1001-1500/1204. Last Person to Fit in the Bus.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | person_name 5 | FROM 6 | ( 7 | SELECT 8 | *, 9 | SUM(weight) OVER ( 10 | ORDER BY 11 | turn 12 | ) AS total_weight 13 | FROM 14 | Queue 15 | ) t 16 | WHERE 17 | total_weight <= 1000 18 | ORDER BY 19 | turn DESC 20 | LIMIT 21 | 1; -------------------------------------------------------------------------------- /1001-1500/1211. Queries Quality and Percentage.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | query_name, 5 | ROUND(AVG(1.0 * rating / position), 2) AS quality, 6 | ROUND( 7 | ( 8 | SUM( 9 | CASE 10 | WHEN rating < 3 THEN 1 11 | ELSE 0 12 | END 13 | ) / COUNT(*) * 100 14 | ), 15 | 2 16 | ) AS poor_query_percentage 17 | FROM 18 | Queries 19 | GROUP BY 20 | query_name; -------------------------------------------------------------------------------- /1001-1500/1251. Average Selling Price.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | u.product_id, 5 | ROUND(SUM(u.units * p.price) / SUM(u.units), 2) as average_price 6 | FROM 7 | UnitsSold u 8 | JOIN Prices p ON u.product_id = p.product_id 9 | AND u.purchase_date BETWEEN p.start_date 10 | AND p.end_date 11 | GROUP BY 12 | u.product_id; -------------------------------------------------------------------------------- /1001-1500/1280. Students and Examinations.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | s.student_id, 5 | s.student_name, 6 | sub.subject_name, 7 | COUNT(e.subject_name) AS attended_exams 8 | FROM 9 | Students s 10 | CROSS JOIN Subjects sub 11 | LEFT JOIN Examinations e ON s.student_id = e.student_id 12 | AND sub.subject_name = e.subject_name 13 | GROUP BY 14 | s.student_id, 15 | sub.subject_name 16 | ORDER BY 17 | s.student_id, 18 | sub.subject_name; -------------------------------------------------------------------------------- /1001-1500/1321. Restaurant Growth.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | # 1321. Restaurant Growth 4 | select 5 | a.visited_on as visited_on, 6 | sum(b.day_sum) as amount, 7 | round(avg(b.day_sum), 2) as average_amount 8 | FROM 9 | ( 10 | select 11 | visited_on, 12 | sum(amount) as day_sum 13 | from 14 | Customer 15 | group by 16 | visited_on 17 | ) a, 18 | ( 19 | select 20 | visited_on, 21 | sum(amount) as day_sum 22 | from 23 | Customer 24 | group by 25 | visited_on 26 | ) b 27 | where 28 | datediff(a.visited_on, b.visited_on) between 0 29 | and 6 30 | group by 31 | a.visited_on 32 | having 33 | count(b.visited_on) = 7 -------------------------------------------------------------------------------- /1001-1500/1327. List the Products Ordered in a Period.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | p.product_name, 5 | SUM(o.unit) AS unit 6 | FROM 7 | Products p 8 | JOIN Orders o ON p.product_id = o.product_id 9 | WHERE 10 | o.order_date BETWEEN '2020-02-01' 11 | AND '2020-02-29' 12 | GROUP BY 13 | p.product_id 14 | HAVING 15 | SUM(o.unit) >= 100; -------------------------------------------------------------------------------- /1001-1500/1341. Movie Rating.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | # 1341. Movie Rating 4 | with movie_rating as ( 5 | select 6 | mr.movie_id, 7 | avg(rating) as avg_rate, 8 | title 9 | from 10 | MovieRating as mr 11 | left join Movies as m on mr.movie_id = m.movie_id 12 | where 13 | created_at between "2020-02-01" 14 | and "2020-02-28" 15 | group by 16 | movie_id 17 | order by 18 | avg_rate desc, 19 | title asc 20 | limit 21 | 1 22 | ), users_rating as ( 23 | select 24 | u.user_id, 25 | u.name, 26 | count(mr.user_id) as rate_count 27 | from 28 | Users as u 29 | left join MovieRating as mr on u.user_id = mr.user_id 30 | group by 31 | mr.user_id 32 | order by 33 | rate_count desc, 34 | name 35 | limit 36 | 1 37 | ) 38 | select 39 | name as "results" 40 | from 41 | users_rating 42 | union 43 | all 44 | select 45 | title 46 | from 47 | movie_rating; -------------------------------------------------------------------------------- /1001-1500/1378. Replace Employee ID With The Unique Identifier.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | EmployeeUNI.unique_id, 5 | Employees.name 6 | FROM 7 | Employees 8 | LEFT JOIN EmployeeUNI ON Employees.id = EmployeeUNI.id -------------------------------------------------------------------------------- /1501-2000/1517. Find Users With Valid E-Mails.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | # 1517. Find Users With Valid E-Mails 4 | select 5 | * 6 | from 7 | Users 8 | where 9 | mail regexp '^[A-Z][A-Z0-9_.-]*[@]leetcode[.]com$'; -------------------------------------------------------------------------------- /1501-2000/1523. Count Odd Numbers in an Interval Range.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1523. Count Odd Numbers in an Interval Range 6 | // Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive). 7 | 8 | // Example 1: 9 | // Input: low = 3, high = 7 10 | // Output: 3 11 | // Explanation: The odd numbers between 3 and 7 are [3,5,7]. 12 | 13 | // Example 2: 14 | // Input: low = 8, high = 10 15 | // Output: 1 16 | // Explanation: The odd numbers between 8 and 10 are [9]. 17 | 18 | // Constraints: 19 | // 0 <= low <= high <= 10^9 20 | 21 | func countOdds(_ low: Int, _ high: Int) -> Int { 22 | var count = 0 23 | 24 | if low % 2 != 0 && high % 2 != 0 { count -= 1 } 25 | if low % 2 != 0 { count += 1 } 26 | if high % 2 != 0 { count += 1 } 27 | 28 | return (count + ((high - low) / 2)) 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /1501-2000/1550. Three Consecutive Odds.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1550. Three Consecutive Odds 6 | // Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. 7 | 8 | // Example 1: 9 | // Input: arr = [2,6,4,1] 10 | // Output: false 11 | // Explanation: There are no three consecutive odds. 12 | 13 | // Example 2: 14 | // Input: arr = [1,2,34,3,4,5,7,23,12] 15 | // Output: true 16 | // Explanation: [5,7,23] are three consecutive odds. 17 | 18 | // Constraints: 19 | // 1 <= arr.length <= 1000 20 | // 1 <= arr[i] <= 1000 21 | 22 | func threeConsecutiveOdds(_ arr: [Int]) -> Bool { 23 | var count = 0 24 | 25 | for num in arr { 26 | if num % 2 != 0 { 27 | count += 1 28 | if count == 3 { return true } 29 | } else { 30 | count = 0 31 | } 32 | } 33 | 34 | return false 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /1501-2000/1556. Thousand Separator.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1556. Thousand Separator 6 | // Given an integer n, add a dot (".") as the thousands separator and return it in string format. 7 | 8 | // Example 1: 9 | // Input: n = 987 10 | // Output: "987" 11 | 12 | // Example 2: 13 | // Input: n = 1234 14 | // Output: "1.234" 15 | 16 | // Example 3: 17 | // Input: n = 123456789 18 | // Output: "123.456.789" 19 | 20 | // Example 4: 21 | // Input: n = 0 22 | // Output: "0" 23 | 24 | // Constraints: 25 | // 0 <= n < 2^31 26 | 27 | func thousandSeparator(_ n: Int) -> String { 28 | let s = [Character]("\(n)".reversed()) 29 | var ans = "" 30 | let n = s.count 31 | 32 | for i in 0.. 15; -------------------------------------------------------------------------------- /1501-2000/1731. The Number of Employees Which Report to Each Employee.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | e.reports_to AS employee_id, 5 | m.name, 6 | COUNT(e.employee_id) AS reports_count, 7 | ROUND(AVG(e.age)) AS average_age 8 | FROM 9 | Employees e 10 | JOIN Employees m ON (e.reports_to = m.employee_id) 11 | GROUP BY 12 | e.reports_to 13 | HAVING 14 | COUNT(e.employee_id) > 0 15 | ORDER BY 16 | employee_id; -------------------------------------------------------------------------------- /1501-2000/1780. Check if Number is a Sum of Powers of Three.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1780. Check if Number is a Sum of Powers of Three 6 | // Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false. 7 | // An integer y is a power of three if there exists an integer x such that y == 3x. 8 | 9 | // Example 1: 10 | // Input: n = 12 11 | // Output: true 12 | // Explanation: 12 = 31 + 32 13 | 14 | // Example 2: 15 | // Input: n = 91 16 | // Output: true 17 | // Explanation: 91 = 30 + 32 + 34 18 | 19 | // Example 3: 20 | // Input: n = 21 21 | // Output: false 22 | 23 | // Constraints: 24 | // 1 <= n <= 10^7 25 | 26 | func checkPowersOfThree(_ n: Int) -> Bool { 27 | var val = n 28 | while val > 0 { 29 | guard val % 3 != 2 else { return false } 30 | val /= 3 31 | } 32 | return true 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /1501-2000/1789. Primary Department for Each Employee.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | employee_id, 5 | department_id 6 | FROM 7 | Employee 8 | WHERE 9 | primary_flag = 'Y' 10 | UNION 11 | SELECT 12 | employee_id, 13 | department_id 14 | FROM 15 | Employee 16 | WHERE 17 | employee_id NOT IN ( 18 | SELECT 19 | employee_id 20 | FROM 21 | Employee 22 | WHERE 23 | primary_flag = 'Y' 24 | ) -------------------------------------------------------------------------------- /1501-2000/1832. Check if the Sentence Is Pangram.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1832. Check if the Sentence Is Pangram 6 | // A pangram is a sentence where every letter of the English alphabet appears at least once. 7 | // Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. 8 | 9 | // Example 1: 10 | // Input: sentence = "thequickbrownfoxjumpsoverthelazydog" 11 | // Output: true 12 | // Explanation: sentence contains at least one of every letter of the English alphabet. 13 | 14 | // Example 2: 15 | // Input: sentence = "leetcode" 16 | // Output: false 17 | 18 | // Constraints: 19 | // 1 <= sentence.length <= 1000 20 | // sentence consists of lowercase English letters. 21 | 22 | func checkIfPangram(_ sentence: String) -> Bool { Set(sentence).count == 26 } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /1501-2000/1837. Sum of Digits in Base K.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1837. Sum of Digits in Base K 6 | // Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. 7 | // After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10. 8 | 9 | // Example 1: 10 | // Input: n = 34, k = 6 11 | // Output: 9 12 | // Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9. 13 | 14 | // Example 2: 15 | // Input: n = 10, k = 10 16 | // Output: 1 17 | // Explanation: n is already in base 10. 1 + 0 = 1. 18 | 19 | // Constraints: 20 | // 1 <= n <= 10^0 21 | // 2 <= k <= 10 22 | 23 | func sumBase(_ n: Int, _ k: Int) -> Int { 24 | var ans = 0 25 | var N = n 26 | 27 | while N > 0 { 28 | ans += N % k 29 | N /= k 30 | } 31 | return ans 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /1501-2000/1907. Count Salary Categories.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | 'Low Salary' AS category, 5 | COUNT(*) AS accounts_count 6 | FROM 7 | Accounts 8 | WHERE 9 | income < 20000 10 | UNION 11 | SELECT 12 | 'Average Salary' AS category, 13 | COUNT(*) AS accounts_count 14 | FROM 15 | Accounts 16 | WHERE 17 | income >= 20000 18 | AND income <= 50000 19 | UNION 20 | SELECT 21 | 'High Salary' AS category, 22 | COUNT(*) AS accounts_count 23 | FROM 24 | Accounts 25 | WHERE 26 | income > 50000; -------------------------------------------------------------------------------- /1501-2000/1934. Confirmation Rate.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | s.user_id, 5 | IFNULL( 6 | ROUND( 7 | CAST( 8 | SUM( 9 | CASE 10 | WHEN c.action = 'confirmed' THEN 1 11 | ELSE 0 12 | END 13 | ) AS FLOAT 14 | ) / COUNT(c.user_id), 15 | 2 16 | ), 17 | 0 18 | ) AS confirmation_rate 19 | FROM 20 | Signups s 21 | LEFT JOIN Confirmations c ON s.user_id = c.user_id 22 | GROUP BY 23 | s.user_id; -------------------------------------------------------------------------------- /1501-2000/1952. Three Divisors.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | 5 | // 1952. Three Divisors 6 | // Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false. 7 | // An integer m is a divisor of n if there exists an integer k such that n = k * m. 8 | 9 | // Example 1: 10 | // Input: n = 2 11 | // Output: false 12 | // Explanation: 2 has only two divisors: 1 and 2. 13 | 14 | // Example 2: 15 | // Input: n = 4 16 | // Output: true 17 | // Explanation: 4 has three divisors: 1, 2, and 4. 18 | 19 | // Constraints: 20 | // 1 <= n <= 10^4 21 | 22 | func isThree(_ n: Int) -> Bool { 23 | var count = 0 24 | 25 | for i in 1...n { 26 | if n % i == 0 { count += 1 } 27 | if count > 3 { break } 28 | } 29 | return count == 3 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /1501-2000/1978. Employees Whose Manager Left the Company.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | # 1978. Employees Whose Manager Left the Company 4 | select 5 | e1.employee_id 6 | from 7 | Employees e1 8 | where 9 | e1.salary < 30000 10 | and manager_id is not null 11 | and not exists( 12 | select 13 | e2.employee_id 14 | from 15 | employees e2 16 | where 17 | e2.employee_id = e1.manager_id 18 | ) 19 | order by 20 | employee_id -------------------------------------------------------------------------------- /2001-2500/2239. Find Closest Number to Zero.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2239. Find Closest Number to Zero 5 | 6 | func findClosestNumber(_ nums: [Int]) -> Int { 7 | var closest = nums[0] 8 | 9 | for num in nums { 10 | if abs(num) < abs(closest) || (abs(num) == abs(closest) && num > closest) { 11 | closest = num 12 | } 13 | } 14 | 15 | return closest 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /2001-2500/2240. Number of Ways to Buy Pens and Pencils.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2240. Number of Ways to Buy Pens and Pencils 5 | 6 | func waysToBuyPensPencils(_ total: Int, _ cost1: Int, _ cost2: Int) -> Int { 7 | var res = 0 8 | for cnt in 0...(total / cost1) { 9 | res += (total - cnt * cost1) / cost2 + 1 10 | } 11 | return res 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /2001-2500/2356. Number of Unique Subjects Taught by Each Teacher.sql: -------------------------------------------------------------------------------- 1 | # MySQL query statement below 2 | # Solution by Sergey Leschev 3 | SELECT 4 | teacher_id, 5 | COUNT(DISTINCT subject_id) AS cnt 6 | FROM 7 | Teacher 8 | GROUP BY 9 | teacher_id -------------------------------------------------------------------------------- /2001-2500/2413. Smallest Even Multiple.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2413. Smallest Even Multiple 5 | 6 | func smallestEvenMultiple(_ n: Int) -> Int { 7 | if n % 2 == 0 { 8 | return n 9 | } 10 | return 2 * n 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /2001-2500/2496. Maximum Value of a String in an Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2496. Maximum Value of a String in an Array 5 | 6 | func maximumValue(_ strs: [String]) -> Int { 7 | var maxValue = 0 8 | 9 | for str in strs { 10 | if let intValue = Int(str) { 11 | maxValue = max(maxValue, intValue) 12 | } else { 13 | maxValue = max(maxValue, str.count) 14 | } 15 | } 16 | 17 | return maxValue 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /2001-2500/2498. Frog Jump II.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2498. Frog Jump II 5 | 6 | func maxJump(_ stones: [Int]) -> Int { 7 | var res = stones[1] - stones[0] // store max difference 8 | for i in stride(from: 3, to: stones.count, by: 2) { 9 | res = max(res, stones[i] - stones[i - 2]) // odd path 10 | } 11 | for i in stride(from: 2, to: stones.count, by: 2) { 12 | res = max(res, stones[i] - stones[i - 2]) // even path 13 | } 14 | return res 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /2501-3000/2513. Minimize the Maximum of Two Arrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2513. Minimize the Maximum of Two Arrays 5 | 6 | func gcd(_ a: Int, _ b: Int) -> Int { 7 | return b == 0 ? a : gcd(b, a % b) 8 | } 9 | 10 | func lcm(_ a: Int, _ b: Int) -> Int { 11 | return a / gcd(a, b) * b 12 | } 13 | 14 | func minimizeSet(_ divisor1: Int, _ divisor2: Int, _ uniqueCnt1: Int, _ uniqueCnt2: Int) -> Int 15 | { 16 | let G = lcm(divisor1, divisor2) 17 | var left = 0 18 | var right = 10_000_000_000 // 10^10 19 | 20 | while left < right { 21 | let middle = (left + right) / 2 22 | 23 | let x = middle - middle / divisor1 >= uniqueCnt1 24 | let y = middle - middle / divisor2 >= uniqueCnt2 25 | let z = middle - middle / G >= uniqueCnt1 + uniqueCnt2 26 | 27 | if x && y && z { 28 | right = middle 29 | } else { 30 | left = middle + 1 31 | } 32 | } 33 | 34 | return left 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /2501-3000/2516. Take K of Each Character From Left and Right.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2516. Take K of Each Character From Left and Right 5 | 6 | func takeCharacters(_ s: String, _ k: Int) -> Int { 7 | var cnt = [0, 0, 0] 8 | let sArray = Array(s) 9 | let sz = s.count 10 | var res = -1 11 | 12 | for ch in sArray { 13 | cnt[Int(ch.asciiValue! - Character("a").asciiValue!)] += 1 14 | } 15 | 16 | if cnt.min()! < k { 17 | return -1 18 | } 19 | 20 | var j = 0 21 | for i in 0.. Int { 7 | let mod = 1_000_000_007 8 | var total = 0 9 | var res = 1 10 | var dp = [Int](repeating: 0, count: k) 11 | dp[0] = 1 12 | 13 | for a in nums { 14 | for i in stride(from: k - 1 - a, through: 0, by: -1) { 15 | dp[i + a] = (dp[i + a] + dp[i]) % mod 16 | } 17 | 18 | res = (res * 2) % mod 19 | total += a 20 | } 21 | 22 | for i in 0.. Int { 7 | let maxNum = nums.max() ?? 0 8 | var primes = Set() 9 | 10 | // Function to check if a number is prime 11 | func isPrime(_ n: Int) -> Bool { 12 | if n < 2 { return false } 13 | for i in 2.. Int { 7 | var n: Int64 = 0 8 | var res: Int = 1 9 | for char in s { 10 | let digit = Int64(String(char))! 11 | n = n * 10 + digit 12 | if n > Int64(k) { 13 | res += 1 14 | n = digit 15 | } 16 | if n > Int64(k) { 17 | return -1 18 | } 19 | } 20 | return res 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /2501-3000/2525. Categorize Box According to Criteria.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2525. Categorize Box According to Criteria 5 | 6 | func categorizeBox(_ length: Int, _ width: Int, _ height: Int, _ mass: Int) -> String { 7 | let volume = Int64(length) * Int64(width) * Int64(height) 8 | var isBulky = false 9 | var isHeavy = false 10 | 11 | if length >= 10000 || width >= 10000 || height >= 10000 || volume >= 1_000_000_000 { 12 | isBulky = true 13 | } 14 | 15 | if mass >= 100 { 16 | isHeavy = true 17 | } 18 | 19 | if isBulky && isHeavy { 20 | return "Both" 21 | } else if !isBulky && !isHeavy { 22 | return "Neither" 23 | } else if isHeavy { 24 | return "Heavy" 25 | } else { 26 | return "Bulky" 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2526. Find Consecutive Integers from a Data Stream.swift: -------------------------------------------------------------------------------- 1 | class DataStream { 2 | 3 | // Solution by Sergey Leschev 4 | // 2526. Find Consecutive Integers from a Data Stream 5 | 6 | let value: Int 7 | let k: Int 8 | var numOccurrences: Int 9 | 10 | init(_ value: Int, _ k: Int) { 11 | self.value = value 12 | self.k = k 13 | self.numOccurrences = 0 14 | } 15 | 16 | func consec(_ num: Int) -> Bool { 17 | if num == value { 18 | numOccurrences += 1 19 | } else { 20 | numOccurrences = 0 21 | } 22 | 23 | return numOccurrences >= k 24 | } 25 | } 26 | 27 | /** 28 | * Your DataStream object will be instantiated and called as such: 29 | * let obj = DataStream(value, k) 30 | * let ret_1: Bool = obj.consec(num) 31 | */ 32 | -------------------------------------------------------------------------------- /2501-3000/2527. Find Xor-Beauty of Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2527. Find Xor-Beauty of Array 5 | 6 | func xorBeauty(_ nums: [Int]) -> Int { 7 | var xor = 0 8 | for num in nums { 9 | xor ^= num 10 | } 11 | return xor 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /2501-3000/2529. Maximum Count of Positive Integer and Negative Integer.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2529. Maximum Count of Positive Integer and Negative Integer 5 | 6 | func maximumCount(_ nums: [Int]) -> Int { 7 | var posCount = 0 8 | var negCount = 0 9 | 10 | for num in nums { 11 | if num > 0 { 12 | posCount += 1 13 | } else if num < 0 { 14 | negCount += 1 15 | } 16 | } 17 | 18 | return max(posCount, negCount) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2535. Difference Between Element Sum and Digit Sum of an Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2535. Difference Between Element Sum and Digit Sum of an Array 5 | 6 | func differenceOfSum(_ nums: [Int]) -> Int { 7 | var elementSum = 0 8 | var digitSum = 0 9 | 10 | for num in nums { 11 | elementSum += num 12 | var currentNum = num 13 | while currentNum > 0 { 14 | digitSum += currentNum % 10 15 | currentNum /= 10 16 | } 17 | } 18 | 19 | return abs(elementSum - digitSum) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /2501-3000/2536. Increment Submatrices by One.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2536. Increment Submatrices by One 5 | // 2-D Range Caching 6 | 7 | func rangeAddQueries(_ n: Int, _ queries: [[Int]]) -> [[Int]] { 8 | var ans = Array(repeating: Array(repeating: 0, count: n), count: n) 9 | 10 | for query in queries { 11 | let r1 = query[0] 12 | let c1 = query[1] 13 | let r2 = query[2] 14 | let c2 = query[3] 15 | ans[r1][c1] += 1 16 | if r2 + 1 < n { ans[r2 + 1][c1] -= 1 } 17 | if c2 + 1 < n { ans[r1][c2 + 1] -= 1 } 18 | if r2 + 1 < n && c2 + 1 < n { ans[r2 + 1][c2 + 1] += 1 } 19 | } 20 | 21 | for r in 1.. Int { 7 | var i = 0 8 | var j = 0 9 | while i < nums1.count && j < nums2.count { 10 | if nums1[i] == nums2[j] { 11 | return nums1[i] 12 | } else if nums1[i] < nums2[j] { 13 | i += 1 14 | } else { 15 | j += 1 16 | } 17 | } 18 | return -1 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2542. Maximum Subsequence Score.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2542. Maximum Subsequence Score 5 | 6 | func maxScore(_ nums1: [Int], _ nums2: [Int], _ k: Int) -> Int { 7 | let a = zip(nums1, nums2).sorted(by: { $0.1 > $1.1 }) 8 | var h = [Int](repeating: 0, count: k) 9 | var s = 0 10 | for i in 0.. h.min()! { 18 | s += x - h.min()! 19 | h[h.firstIndex(of: h.min()!)!] = x 20 | ans = max(ans, s * y) 21 | } 22 | } 23 | return ans 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /2501-3000/2543. Check if Point Is Reachable.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2543. Check if Point Is Reachable 5 | 6 | func isReachable(_ targetX: Int, _ targetY: Int) -> Bool { 7 | var x = decrease(targetX) 8 | var y = decrease(targetY) 9 | 10 | while true { 11 | if x == 1 || y == 1 { 12 | return true 13 | } 14 | 15 | if x == y { 16 | return false // The coordinates won't change, we are stuck 17 | } 18 | 19 | let newCoordinate = decrease(x + y) 20 | 21 | // Putting the new coordinate to the place of the biggest current coordinate 22 | if x < y { 23 | y = newCoordinate 24 | } else { 25 | x = newCoordinate 26 | } 27 | } 28 | } 29 | 30 | func decrease(_ value: Int) -> Int { 31 | var result = value 32 | while result % 2 == 0 { 33 | result = result >> 1 // This means division by 2 34 | } 35 | return result 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /2501-3000/2544. Alternating Digit Sum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2544. Alternating Digit Sum 5 | 6 | func alternateDigitSum(_ n: Int) -> Int { 7 | var res = 0 8 | var sign = 1 9 | var num = n 10 | 11 | while num > 0 { 12 | sign *= -1 13 | res += sign * (num % 10) 14 | num /= 10 15 | } 16 | 17 | return sign * res 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /2501-3000/2545. Sort the Students by Their Kth Score.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2545. Sort the Students by Their Kth Score 5 | 6 | // Time complexity: O(quick sort) 7 | // Space complexity: O(quick sort) 8 | 9 | func sortTheStudents(_ score: [[Int]], _ k: Int) -> [[Int]] { 10 | var sortedScore = score 11 | sortedScore.sort(by: { $0[k] > $1[k] }) 12 | return sortedScore 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /2501-3000/2546. Apply Bitwise Operations to Make Strings Equal.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2546. Apply Bitwise Operations to Make Strings Equal 5 | 6 | func makeStringsEqual(_ s: String, _ target: String) -> Bool { 7 | s.contains("1") == target.contains("1") 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /2501-3000/2549. Count Distinct Numbers on Board.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2549. Count Distinct Numbers on Board 5 | 6 | func distinctIntegers(_ n: Int) -> Int { 7 | var board = Set() 8 | board.insert(n) 9 | var prevNumbers = [n] 10 | for _ in 1...Int(1e9) { 11 | var newNumbers = Set() 12 | for x in prevNumbers { 13 | for i in stride(from: 1, through: n, by: x % 2 == 0 ? 2 : 1) { 14 | if x % i == 1 { 15 | newNumbers.insert(i) 16 | } 17 | } 18 | } 19 | if newNumbers.isEmpty { 20 | break // no new numbers to add 21 | } 22 | prevNumbers = Array(newNumbers) 23 | board.formUnion(newNumbers) 24 | } 25 | return board.count 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2550. Count Collisions of Monkeys on a Polygon.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2550. Count Collisions of Monkeys on a Polygon 5 | 6 | // Time complexity: O(logn) 7 | // Space complexity: O(1) 8 | 9 | func monkeyMove(_ n: Int) -> Int { 10 | let mod = 1_000_000_007 11 | var res: Int64 = 1 12 | var base: Int64 = 2 13 | var n = n 14 | 15 | while n > 0 { 16 | if n % 2 == 1 { 17 | res = (res * base) % Int64(mod) 18 | } 19 | base = (base * base) % Int64(mod) 20 | n >>= 1 21 | } 22 | 23 | let finalRes = (res - 2 + Int64(mod)) % Int64(mod) 24 | return Int(finalRes) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /2501-3000/2551. Put Marbles in Bags.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2551. Put Marbles in Bags 5 | 6 | func putMarbles(_ weights: [Int], _ k: Int) -> Int { 7 | let n = weights.count 8 | if k == 1 || n == k { 9 | return 0 10 | } 11 | 12 | var candidates: [Int] = [] 13 | for i in 0..<(n - 1) { 14 | candidates.append(weights[i] + weights[i + 1]) 15 | } 16 | candidates.sort() 17 | 18 | var mins: Int64 = 0 19 | var maxs: Int64 = 0 20 | for i in 0..<(k - 1) { 21 | mins += Int64(candidates[i]) 22 | maxs += Int64(candidates[n - 2 - i]) 23 | } 24 | 25 | return Int(maxs - mins) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2552. Count Increasing Quadruplets.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2552. Count Increasing Quadruplets 5 | 6 | // Time complexity: O(n^2) 7 | // Space complexity: O(n) 8 | 9 | func countQuadruplets(_ nums: [Int]) -> Int { 10 | let n = nums.count 11 | var cnt = Array(repeating: 0, count: n) 12 | var ans = 0 13 | 14 | for j in 0.. nums[i] { 19 | prevSmall += 1 20 | ans += cnt[i] 21 | } else if nums[j] < nums[i] { 22 | cnt[i] += prevSmall 23 | } 24 | } 25 | } 26 | 27 | return ans 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2553. Separate the Digits in an Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2553. Separate the Digits in an Array 5 | 6 | func separateDigits(_ nums: [Int]) -> [Int] { 7 | var answer = [Int]() 8 | for num in nums { 9 | var digits = [Int]() 10 | var n = num 11 | while n > 0 { 12 | digits.append(n % 10) 13 | n /= 10 14 | } 15 | digits.reverse() 16 | answer.append(contentsOf: digits) 17 | } 18 | return answer 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2554. Maximum Number of Integers to Choose From a Range I.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2554. Maximum Number of Integers to Choose From a Range I 5 | 6 | // Time complexity: O(N logN) 7 | // Space complexity: O(1) 8 | 9 | func maxCount(_ banned: [Int], _ n: Int, _ maxSum: Int) -> Int { 10 | let sortedBanned = banned.sorted() 11 | var ans = 0 12 | var j = 0 13 | var remainingMaxSum = maxSum 14 | 15 | for i in 1...n { 16 | if j == sortedBanned.count || i < sortedBanned[j], remainingMaxSum - i >= 0 { 17 | ans += 1 18 | remainingMaxSum -= i 19 | } else { 20 | while j < sortedBanned.count && i >= sortedBanned[j] { 21 | j += 1 22 | } 23 | } 24 | } 25 | 26 | return ans 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2501-3000/2556. Disconnect Path in a Binary Matrix by at Most One Flip.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2556. Disconnect Path in a Binary Matrix by at Most One Flip 5 | // Time complexity: O(M * N) 6 | // Space complexity: O(1) 7 | 8 | func isPossibleToCutPath(_ grid: [[Int]]) -> Bool { 9 | func dfs(_ grid: inout [[Int]], _ i: Int, _ j: Int) -> Bool { 10 | if i + 1 == grid.count && j + 1 == grid[0].count { 11 | return true 12 | } 13 | if i >= grid.count || j >= grid[0].count || grid[i][j] == 0 { 14 | return false 15 | } 16 | grid[i][j] = 0 17 | return dfs(&grid, i + 1, j) || dfs(&grid, i, j + 1) 18 | } 19 | 20 | var mutableGrid = grid 21 | if !dfs(&mutableGrid, 0, 0) { 22 | return true 23 | } 24 | mutableGrid[0][0] = 1 25 | return !dfs(&mutableGrid, 0, 0) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2559. Count Vowel Strings in Ranges.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2559. Count Vowel Strings in Ranges 5 | 6 | func check(_ c: Character) -> Bool { 7 | return c == "a" || c == "e" || c == "i" || c == "o" || c == "u" 8 | } 9 | 10 | func vowelStrings(_ words: [String], _ queries: [[Int]]) -> [Int] { 11 | var v = [0] 12 | for w in words { 13 | if check(w.first!) && check(w.last!) { 14 | v.append(v.last! + 1) 15 | } else { 16 | v.append(v.last!) 17 | } 18 | } 19 | 20 | var ans = [Int]() 21 | for q in queries { 22 | ans.append(v[q[1] + 1] - v[q[0]]) 23 | } 24 | 25 | return ans 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2561. Rearranging Fruits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2561. Rearranging Fruits 5 | 6 | func minCost(_ basket1: [Int], _ basket2: [Int]) -> Int { 7 | var cnt: [Int: Int] = [:] 8 | for c in basket1 { 9 | cnt[c, default: 0] += 1 10 | } 11 | for c in basket2 { 12 | cnt[c, default: 0] -= 1 13 | } 14 | var last: [Int] = [] 15 | for (k, v) in cnt { 16 | if v % 2 != 0 { 17 | return -1 18 | } 19 | for _ in 0.. Int { 7 | var concatValue = 0 8 | var nums = nums 9 | 10 | while nums.count > 0 { 11 | if nums.count == 1 { 12 | concatValue += nums[0] 13 | nums.removeFirst() 14 | } else { 15 | let concatNum = Int(String(nums[0]) + String(nums[nums.count - 1]))! 16 | concatValue += concatNum 17 | nums.removeFirst() 18 | nums.removeLast() 19 | } 20 | } 21 | 22 | return concatValue 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /2501-3000/2563. Count the Number of Fair Pairs.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2563. Count the Number of Fair Pairs 5 | // Time complexity: O(sort) 6 | 7 | func countFairPairs(_ nums: [Int], _ lower: Int, _ upper: Int) -> Int { 8 | var count = 0 9 | 10 | func countLess(_ nums: [Int], _ val: Int) -> Int { 11 | var res = 0 12 | var i = 0 13 | var j = nums.count - 1 14 | 15 | while i < j { 16 | if nums[i] + nums[j] > val { 17 | j -= 1 18 | } else { 19 | res += j - i 20 | i += 1 21 | } 22 | } 23 | 24 | return res 25 | } 26 | 27 | let sortedNums = nums.sorted() 28 | count = countLess(sortedNums, upper) - countLess(sortedNums, lower - 1) 29 | 30 | return count 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /2501-3000/2567. Minimum Score by Changing Two Elements.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2567. Minimum Score by Changing Two Elements 5 | 6 | func minimizeSum(_ nums: [Int]) -> Int { 7 | var s1 = Int.max 8 | var s2 = Int.max 9 | var s3 = Int.max 10 | var l1 = 0 11 | var l2 = 0 12 | var l3 = 0 13 | 14 | for n in nums { 15 | if s1 > n { 16 | s3 = s2 17 | s2 = s1 18 | s1 = n 19 | } else if s2 > n { 20 | s3 = s2 21 | s2 = n 22 | } else if s3 > n { 23 | s3 = n 24 | } 25 | 26 | if l1 < n { 27 | l3 = l2 28 | l2 = l1 29 | l1 = n 30 | } else if l2 < n { 31 | l3 = l2 32 | l2 = n 33 | } else if l3 < n { 34 | l3 = n 35 | } 36 | } 37 | 38 | return min(l1 - s3, l3 - s1, l2 - s2) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /2501-3000/2568. Minimum Impossible OR.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2568. Minimum Impossible OR 5 | 6 | // Time Complexity: O(32n) 7 | // Space Complexity: O(32n) 8 | 9 | func minImpossibleOR(_ nums: [Int]) -> Int { 10 | var numsSet = Set(nums) 11 | var result = 1 12 | 13 | while true { 14 | if !numsSet.contains(result) { 15 | return result 16 | } 17 | result <<= 1 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2570. Merge Two 2D Arrays by Summing Values.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2570. Merge Two 2D Arrays by Summing Values 5 | 6 | func mergeArrays(_ nums1: [[Int]], _ nums2: [[Int]]) -> [[Int]] { 7 | var idToSum = [Int: Int]() 8 | 9 | // add values from nums1 10 | for num in nums1 { 11 | idToSum[num[0], default: 0] += num[1] 12 | } 13 | 14 | // add values from nums2 15 | for num in nums2 { 16 | idToSum[num[0], default: 0] += num[1] 17 | } 18 | 19 | // convert dictionary back to array 20 | var result = [[Int]]() 21 | for (id, sum) in idToSum.sorted(by: { $0.key < $1.key }) { 22 | result.append([id, sum]) 23 | } 24 | 25 | return result 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2571. Minimum Operations to Reduce an Integer to 0.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2571. Minimum Operations to Reduce an Integer to 0 5 | 6 | // Time Complexity: O(logn) 7 | // Space Complexity: O(1) 8 | 9 | func minOperations(_ n: Int) -> Int { 10 | var res = 0 11 | var num = n 12 | 13 | while num > 0 { 14 | if num % 2 == 0 { 15 | num >>= 1 16 | } else if (num & 2) > 0 { 17 | num += 1 18 | res += 1 19 | } else { 20 | res += 1 21 | num >>= 2 22 | } 23 | } 24 | 25 | return res 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2574. Left and Right Sum Differences.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2574. Left and Right Sum Differences 5 | 6 | func leftRigthDifference(_ nums: [Int]) -> [Int] { 7 | var leftSum = [Int](repeating: 0, count: nums.count) 8 | var rightSum = [Int](repeating: 0, count: nums.count) 9 | 10 | // calculate the left sum of each element 11 | for i in 1.. Int { 7 | var currentIndex = 1 8 | var direction = 1 9 | var remainingTime = time 10 | 11 | while remainingTime > 0 { 12 | if currentIndex == 1 && direction == -1 { 13 | // If the pillow reaches the beginning of the line 14 | // while passing from right to left, change direction 15 | direction = 1 16 | } else if currentIndex == n && direction == 1 { 17 | // If the pillow reaches the end of the line 18 | // while passing from left to right, change direction 19 | direction = -1 20 | } else { 21 | // Otherwise, just pass the pillow to the next person 22 | currentIndex += direction 23 | remainingTime -= 1 24 | } 25 | } 26 | 27 | return currentIndex 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2585. Number of Ways to Earn Points.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2585. Number of Ways to Earn Points 5 | 6 | func waysToReachTarget(_ target: Int, _ types: [[Int]]) -> Int { 7 | let mod = 1_000_000_007 8 | var dp = Array(repeating: 0, count: target + 1) 9 | dp[0] = 1 10 | 11 | for type in types { 12 | let count = type[0] 13 | let marks = type[1] 14 | for j in stride(from: target, through: marks, by: -1) { 15 | for k in stride(from: 1, through: count, by: 1) { 16 | if j - k * marks >= 0 { 17 | dp[j] = (dp[j] + dp[j - k * marks]) % mod 18 | } 19 | } 20 | } 21 | } 22 | 23 | return dp[target] 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /2501-3000/2586. Count the Number of Vowel Strings in Range.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2586. Count the Number of Vowel Strings in Range 5 | 6 | func vowelStrings(_ words: [String], _ left: Int, _ right: Int) -> Int { 7 | let vowels: Set = ["a", "e", "i", "o", "u"] 8 | var count = 0 9 | 10 | // Iterate over words in the range [left, right] 11 | for i in left...right { 12 | let word = words[i] 13 | 14 | // Check if the first and last characters of the word are vowels 15 | if vowels.contains(word.first ?? Character("")) 16 | && vowels.contains(word.last ?? Character("")) 17 | { 18 | count += 1 19 | } 20 | } 21 | 22 | return count 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /2501-3000/2595. Number of Even and Odd Bits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2595. Number of Even and Odd Bits 5 | 6 | func evenOddBit(_ n: Int) -> [Int] { 7 | var even = 0 8 | var odd = 0 9 | var num = n 10 | var i = 0 11 | while num > 0 { 12 | if num & 1 == 1 { 13 | if i % 2 == 0 { 14 | even += 1 15 | } else { 16 | odd += 1 17 | } 18 | } 19 | num >>= 1 20 | i += 1 21 | } 22 | return [even, odd] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /2501-3000/2600. K Items With the Maximum Sum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2600. K Items With the Maximum Sum 5 | 6 | func kItemsWithMaximumSum(_ numOnes: Int, _ numZeros: Int, _ numNegOnes: Int, _ k: Int) -> Int { 7 | let ones = min(numOnes, k) 8 | let zeros = min(numZeros, k - ones) 9 | let negOnes = min(numNegOnes, k - ones - zeros) 10 | return ones - negOnes + min(numOnes - ones, k - ones) 11 | - min(numNegOnes - negOnes, k - ones - zeros - negOnes) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /2501-3000/2605. Form Smallest Number From Two Digit Arrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2605. Form Smallest Number From Two Digit Arrays 5 | // Time complexity: O(1), Size of both arrays is less than 10. 6 | // Space complexity: O(1) 7 | 8 | func minNumber(_ nums1: [Int], _ nums2: [Int]) -> Int { 9 | var freq = Array(repeating: 0, count: 10) 10 | 11 | for num in nums1 { 12 | freq[num] += 1 13 | } 14 | 15 | for num in nums2 { 16 | freq[num] += 1 17 | } 18 | 19 | var k = 2 20 | var ans = 0 21 | let mn1 = nums1.min()! 22 | let mn2 = nums2.min()! 23 | 24 | for i in 1...9 { 25 | if freq[i] == 2 { 26 | return i 27 | } 28 | } 29 | 30 | let minNumber = min(mn1, mn2) 31 | let maxNumber = max(mn1, mn2) 32 | return minNumber * 10 + maxNumber 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /2501-3000/2606. Find the Substring With Maximum Cost.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2606. Find the Substring With Maximum Cost 5 | 6 | func maximumCostSubstring(_ s: String, _ chars: String, _ vals: [Int]) -> Int { 7 | var v = Array(1...26) // 1-indexed alphabet values 8 | for (i, ch) in chars.enumerated() { 9 | v[Int(ch.asciiValue! - Character("a").asciiValue!)] = vals[i] 10 | } 11 | 12 | var maxCost = 0 13 | var cost = 0 14 | 15 | for ch in s { 16 | cost = max(0, cost + v[Int(ch.asciiValue! - Character("a").asciiValue!)]) 17 | maxCost = max(maxCost, cost) 18 | } 19 | 20 | return maxCost 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /2501-3000/2607. Make K-Subarray Sums Equal.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2607. Make K-Subarray Sums Equal 5 | 6 | func makeSubKSumEqual(_ arr: [Int], _ k: Int) -> Int { 7 | var arrCopy = arr // Create a mutable copy of the array 8 | var res: Int = 0 9 | for i in 0.. [[Int]] { 7 | var count = [Int](repeating: 0, count: nums.count + 10) 8 | var res = [[Int]]() 9 | 10 | for a in nums { 11 | if res.count <= count[a] { 12 | res.append([]) 13 | } 14 | res[count[a]].append(a) 15 | count[a] += 1 16 | } 17 | 18 | return res 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2611. Mice and Cheese.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2611. Mice and Cheese 5 | 6 | func miceAndCheese(_ reward1: [Int], _ reward2: [Int], _ k: Int) -> Int { 7 | var rewardsDiff = [Int]() 8 | var totalReward = 0 9 | 10 | for i in 0..) 16 | 17 | for i in 0.. Int { 9 | let sortedNums = nums.sorted() 10 | var left = 0 11 | var right = sortedNums.last! - sortedNums.first! 12 | 13 | while left < right { 14 | let mid = (left + right) / 2 15 | var k = 0 16 | var i = 1 17 | 18 | while i < sortedNums.count && k < p { 19 | if sortedNums[i] - sortedNums[i - 1] <= mid { 20 | k += 1 21 | i += 2 22 | } else { 23 | i += 1 24 | } 25 | } 26 | 27 | if k >= p { 28 | right = mid 29 | } else { 30 | left = mid + 1 31 | } 32 | } 33 | 34 | return left 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /2501-3000/2618. Check if Object Instance of Class.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2618. Check if Object Instance of Class 3 | 4 | function checkIfInstanceOf(obj: any, classFunction: any): boolean { 5 | if (obj === null || obj === undefined || classFunction === null || classFunction === undefined) { 6 | return false 7 | } 8 | 9 | let prototype = Object.getPrototypeOf(obj) 10 | 11 | while (prototype != null) { 12 | if (prototype.constructor === classFunction) { 13 | return true 14 | } 15 | prototype = Object.getPrototypeOf(prototype) 16 | } 17 | 18 | return false 19 | } 20 | 21 | /** 22 | * checkIfInstanceOf(new Date(), Date); // true 23 | */ 24 | -------------------------------------------------------------------------------- /2501-3000/2619. Array Prototype Last.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2619. Array Prototype Last 3 | 4 | declare global { 5 | interface Array { 6 | last(): T | -1 7 | } 8 | } 9 | 10 | Array.prototype.last = function () { 11 | if (this.length === 0) { 12 | return -1 13 | } else { 14 | return this[this.length - 1] 15 | } 16 | } 17 | 18 | /** 19 | * const arr = [1, 2, 3]; 20 | * arr.last(); // 3 21 | */ 22 | -------------------------------------------------------------------------------- /2501-3000/2620. Counter.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2620. Counter 3 | 4 | function createCounter(n: number): () => number { 5 | let count = n 6 | return function () { 7 | return count++ 8 | } 9 | } 10 | 11 | /** 12 | * const counter = createCounter(10) 13 | * counter() // 10 14 | * counter() // 11 15 | * counter() // 12 16 | */ 17 | -------------------------------------------------------------------------------- /2501-3000/2621. Sleep.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2621. Sleep 3 | 4 | async function sleep(millis: number): Promise { 5 | return new Promise(resolve => setTimeout(resolve, millis)) 6 | } 7 | 8 | /** 9 | * let t = Date.now() 10 | * sleep(100).then(() => console.log(Date.now() - t)) // 100 11 | */ 12 | -------------------------------------------------------------------------------- /2501-3000/2623. Memoize.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2623. Memoize 3 | 4 | type Fn = (...params: any) => any 5 | 6 | function memoize(fn: Fn): Fn { 7 | const cache = new Map() 8 | return function (...args) { 9 | const key = JSON.stringify(args) 10 | if (cache.has(key)) { 11 | return cache.get(key) 12 | } 13 | const result = fn(...args) 14 | cache.set(key, result) 15 | return result 16 | } 17 | } 18 | 19 | /** 20 | * let callCount = 0; 21 | * const memoizedFn = memoize(function (a, b) { 22 | * callCount += 1; 23 | * return a + b; 24 | * }) 25 | * memoizedFn(2, 3) // 5 26 | * memoizedFn(2, 3) // 5 27 | * console.log(callCount) // 1 28 | */ 29 | -------------------------------------------------------------------------------- /2501-3000/2625. Flatten Deeply Nested Array.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2625. Flatten Deeply Nested Array 3 | 4 | type MultiDimensionalArray = (number | MultiDimensionalArray)[] 5 | 6 | const flat = (arr: MultiDimensionalArray, n: number): MultiDimensionalArray => { 7 | const result: MultiDimensionalArray = [] 8 | 9 | for (const item of arr) { 10 | if (Array.isArray(item) && n > 0) { 11 | result.push(...flat(item, n - 1)) 12 | } else { 13 | result.push(item) 14 | } 15 | } 16 | 17 | return result 18 | } 19 | -------------------------------------------------------------------------------- /2501-3000/2627. Debounce.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2627. Debounce 3 | 4 | type DebouncedFunction any> = (...args: Parameters) => void 5 | 6 | function debounce any>(fn: F, t: number): DebouncedFunction { 7 | let timer: NodeJS.Timeout | null 8 | 9 | return function (this: any, ...args: Parameters) { 10 | if (timer) { 11 | clearTimeout(timer) 12 | timer = null 13 | } 14 | 15 | timer = setTimeout(() => { 16 | fn.apply(this, args) 17 | }, t) 18 | } 19 | } 20 | 21 | /** 22 | * const log = debounce(console.log, 100); 23 | * log('Hello'); // cancelled 24 | * log('Hello'); // cancelled 25 | * log('Hello'); // Logged at t=100ms 26 | */ 27 | -------------------------------------------------------------------------------- /2501-3000/2628. JSON Deep Equal.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2628. JSON Deep Equal 3 | 4 | function areDeeplyEqual(o1: any, o2: any): boolean { 5 | if (o1 === o2) { 6 | return true 7 | } 8 | 9 | if (typeof o1 !== typeof o2) { 10 | return false 11 | } 12 | 13 | if (o1 === null || o2 === null || typeof o1 !== 'object') { 14 | return false 15 | } 16 | 17 | const keys1 = Object.keys(o1) 18 | const keys2 = Object.keys(o2) 19 | if (keys1.length !== keys2.length) { 20 | return false 21 | } 22 | 23 | if (o1.constructor !== o2.constructor) { 24 | return false 25 | } 26 | 27 | for (const key of keys1) { 28 | if (!o2.hasOwnProperty(key) || !areDeeplyEqual(o1[key], o2[key])) { 29 | return false 30 | } 31 | } 32 | 33 | return true 34 | } 35 | -------------------------------------------------------------------------------- /2501-3000/2629. Function Composition.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2629. Function Composition 3 | 4 | type F = (x: number) => number 5 | 6 | function compose(functions: F[]): F { 7 | return functions.reduceRight( 8 | (prevFn, nextFn) => { 9 | return x => nextFn(prevFn(x)) 10 | }, 11 | x => x 12 | ) 13 | } 14 | 15 | /** 16 | * const fn = compose([x => x + 1, x => 2 * x]) 17 | * fn(4) // 9 18 | */ 19 | -------------------------------------------------------------------------------- /2501-3000/2631. Group By.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2631. Group By 3 | 4 | declare global { 5 | interface Array { 6 | groupBy(fn: (item: T) => string): Record 7 | } 8 | } 9 | 10 | Array.prototype.groupBy = function (fn) { 11 | return this.reduce((result, item) => { 12 | const key = fn(item) 13 | if (!result[key]) { 14 | result[key] = [] 15 | } 16 | result[key].push(item) 17 | return result 18 | }, {}) 19 | } 20 | 21 | /** 22 | * [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]} 23 | */ 24 | -------------------------------------------------------------------------------- /2501-3000/2632. Curry.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2632. Curry 3 | 4 | function curry(fn: Function): Function { 5 | return function curried(...args: any[]) { 6 | if (args.length >= fn.length) { 7 | return fn(...args) 8 | } 9 | return function (...innerArgs: any[]) { 10 | return curried(...args, ...innerArgs) 11 | } 12 | } 13 | } 14 | 15 | /** 16 | * function sum(a, b) { return a + b; } 17 | * const csum = curry(sum); 18 | * csum(1)(2) // 3 19 | */ 20 | -------------------------------------------------------------------------------- /2501-3000/2633. Convert Object to JSON String.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2633. Convert Object to JSON String 3 | 4 | function jsonStringify(object: any): string { 5 | if (object === null || object === undefined) { 6 | return 'null' 7 | } else if (typeof object === 'boolean' || typeof object === 'number') { 8 | return object.toString() 9 | } else if (typeof object === 'string') { 10 | return `"${object}"` 11 | } else if (Array.isArray(object)) { 12 | const values = object.map(jsonStringify) 13 | return `[${values.join(',')}]` 14 | } else if (typeof object === 'object') { 15 | const keys = Object.keys(object) 16 | const values = keys.map(key => `${jsonStringify(key)}:${jsonStringify(object[key])}`) 17 | return `{${values.join(',')}}` 18 | } else { 19 | throw new Error(`Invalid type: ${typeof object}`) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /2501-3000/2634. Filter Elements from Array.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2634. Filter Elements from Array 3 | 4 | function filter(arr: number[], fn: (n: number, i: number) => any): number[] { 5 | const result: number[] = [] 6 | for (let i = 0; i < arr.length; i++) { 7 | if (fn(arr[i], i)) { 8 | result.push(arr[i]) 9 | } 10 | } 11 | return result 12 | } 13 | -------------------------------------------------------------------------------- /2501-3000/2635. Apply Transform Over Each Element in Array.ts: -------------------------------------------------------------------------------- 1 | // Solution by Sergey Leschev 2 | // 2635. Apply Transform Over Each Element in Array 3 | 4 | function map(arr: number[], fn: (n: number, i: number) => number): number[] { 5 | const result: number[] = [] 6 | for (let i = 0; i < arr.length; i++) { 7 | result.push(fn(arr[i], i)) 8 | } 9 | return result 10 | } 11 | -------------------------------------------------------------------------------- /2501-3000/2640. Find the Score of All Prefixes of an Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2640. Find the Score of All Prefixes of an Array 5 | // Time complexity: O(n) 6 | // Space complexity: O(n) 7 | 8 | func findPrefixScore(_ nums: [Int]) -> [Int] { 9 | var m = 0 10 | var conver = [Int]() 11 | for x in nums { 12 | m = max(m, x) 13 | conver.append(x + m) 14 | } 15 | 16 | var prefixSum = 0 17 | return conver.map { score in 18 | prefixSum += score 19 | return prefixSum 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /2501-3000/2645. Minimum Additions to Make Valid String.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2645. Minimum Additions to Make Valid String 5 | // Time Complexity: O(n) 6 | // Space Complexity: O(1) 7 | 8 | func addMinimum(_ word: String) -> Int { 9 | var k = 0 10 | var prev: Character = "z" 11 | for char in word { 12 | k += char.asciiValue! <= prev.asciiValue! ? 1 : 0 13 | prev = char 14 | } 15 | return k * 3 - word.count 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /2501-3000/2653. Sliding Subarray Beauty.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2653. Sliding Subarray Beauty 5 | // Time complexity: O(n * 50) 6 | // Space complexity: O(n - k + 1 + 50) 7 | 8 | func getSubarrayBeauty(_ nums: [Int], _ k: Int, _ x: Int) -> [Int] { 9 | var counter = [Int](repeating: 0, count: 50) 10 | var ans = [Int](repeating: 0, count: nums.count - k + 1) 11 | 12 | for i in 0..= 0 && nums[i - k] < 0 { 18 | counter[nums[i - k] + 50] -= 1 19 | } 20 | 21 | if i - k + 1 < 0 { 22 | continue 23 | } 24 | 25 | var count = 0 26 | for j in 0..<50 { 27 | count += counter[j] 28 | if count >= x { 29 | ans[i - k + 1] = j - 50 30 | break 31 | } 32 | } 33 | } 34 | 35 | return ans 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /2501-3000/2657. Find the Prefix Common Array of Two Arrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2657. Find the Prefix Common Array of Two Arrays 5 | // Time complexity: O(n) 6 | // Space complexity: O(n) 7 | 8 | func findThePrefixCommonArray(_ A: [Int], _ B: [Int]) -> [Int] { 9 | let n = A.count 10 | var aux = [Int](repeating: 0, count: n + 1) 11 | var ans = [Int](repeating: 0, count: n) 12 | var cmn = 0 13 | 14 | for i in 0.. Int { 10 | guard r >= 0 && c >= 0 && r < grid.count && c < grid[0].count && grid[r][c] > 0 else { 11 | return 0 12 | } 13 | 14 | var res = grid[r][c] 15 | grid[r][c] = 0 16 | 17 | for d in dir { 18 | res += dfs(&grid, r + d[0], c + d[1]) 19 | } 20 | 21 | return res 22 | } 23 | 24 | func findMaxFish(_ grid: [[Int]]) -> Int { 25 | var ans = 0 26 | var mutableGrid = grid 27 | 28 | for i in 0.. Int { 7 | var sortedIndex = Array(nums.enumerated()).sorted { $0.element < $1.element }.map { 8 | $0.offset 9 | } 10 | var s = 0 11 | var curr = 0 12 | var currLoopSubtract = 0 13 | var loopedSubtract = 0 14 | 15 | for ind in sortedIndex { 16 | if curr <= ind { 17 | s += ind - curr + 1 18 | curr = ind + 1 19 | currLoopSubtract += 1 20 | } else { // wrap around 21 | s += ind + (nums.count - curr) + 1 22 | curr = ind + 1 23 | s -= loopedSubtract 24 | loopedSubtract += currLoopSubtract 25 | currLoopSubtract = 1 26 | } 27 | } 28 | 29 | s -= (curr - currLoopSubtract) 30 | return s 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /2501-3000/2661. First Completely Painted Row or Column.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2661. First Completely Painted Row or Column 5 | 6 | func firstCompleteIndex(_ arr: [Int], _ mat: [[Int]]) -> Int { 7 | var mpr = [Int: Int]() 8 | var mpc = [Int: Int]() 9 | var mprc = [Int: Int]() 10 | var mpcc = [Int: Int]() 11 | 12 | for i in 0.. String { 7 | var ch = Array(s.utf8) 8 | var i = ch.count - 1 9 | 10 | while i >= 0 { 11 | ch[i] += 1 12 | if ch[i] - 97 == k { 13 | i -= 1 14 | } else if (i - 1 < 0 || ch[i - 1] != ch[i]) && (i - 2 < 0 || ch[i - 2] != ch[i]) { 15 | break 16 | } 17 | } 18 | 19 | if i < 0 { 20 | return "" 21 | } 22 | 23 | for j in (i + 1).. = [97, 98, 99] 25 | if j - 2 >= 0 { 26 | set.remove(ch[j - 2]) 27 | } 28 | if j - 1 >= 0 { 29 | set.remove(ch[j - 1]) 30 | } 31 | ch[j] = set.min()! 32 | } 33 | 34 | return String(bytes: ch, encoding: .utf8)! 35 | } 36 | } -------------------------------------------------------------------------------- /2501-3000/2672. Number of Adjacent Elements With the Same Color.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2672. Number of Adjacent Elements With the Same Color 5 | // Time complexity: O(n) 6 | // Space complexity: O(n) 7 | 8 | func colorTheArray(_ n: Int, _ queries: [[Int]]) -> [Int] { 9 | var nums = [Int](repeating: 0, count: n) 10 | var c = 0 11 | var result = [Int]() 12 | 13 | for query in queries { 14 | let index = query[0] 15 | let color = query[1] 16 | 17 | let pre = index > 0 ? nums[index - 1] : 0 18 | let nex = index < n - 1 ? nums[index + 1] : 0 19 | 20 | if nums[index] != 0 && nums[index] == pre { c -= 1 } 21 | if nums[index] != 0 && nums[index] == nex { c -= 1 } 22 | 23 | nums[index] = color 24 | 25 | if nums[index] == pre { c += 1 } 26 | if nums[index] == nex { c += 1 } 27 | 28 | result.append(c) 29 | } 30 | 31 | return result 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /2501-3000/2673. Make Costs of Paths Equal in a Binary Tree.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2673. Make Costs of Paths Equal in a Binary Tree 5 | // DFS 6 | // Time complexity: O(n) 7 | // Space complexity: O(h) 8 | 9 | var res: Int = 0 10 | 11 | func minIncrements(_ n: Int, _ cost: [Int]) -> Int { 12 | // Helper function to perform the depth-first search (DFS) 13 | func dfs(_ i: Int) -> Int { 14 | if i >= cost.count { return 0 } 15 | let a = dfs(2 * i + 1) 16 | let b = dfs(2 * i + 2) 17 | res += abs(a - b) 18 | return cost[i] + max(a, b) 19 | } 20 | 21 | dfs(0) 22 | return res 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /2501-3000/2679. Sum in a Matrix.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2679. Sum in a Matrix 5 | 6 | // Time complexity: O(r ∗ c logc) as we need to sort each row and sorting is the dominating factor. 7 | // Space complexity: O(c) as we need to keep the max for each column. 8 | // Where: r rows and c columns 9 | 10 | func matrixSum(_ nums: [[Int]]) -> Int { 11 | let cols = nums[0].count 12 | var maxs = Array(repeating: 0, count: cols) 13 | var score = 0 14 | 15 | for row in nums { 16 | let sortedRow = row.sorted() 17 | for c in 0.. Int { 7 | var res: Int64 = 0 8 | var s: Int64 = 0 9 | let base: Int64 = 1_000_000_007 10 | let sortedNums = nums.sorted() 11 | 12 | for x in sortedNums { 13 | res = (res + (s + Int64(x)) * Int64(x) % base * Int64(x) % base) % base 14 | s = (s * 2 + Int64(x)) % base 15 | } 16 | 17 | return Int(res) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /2501-3000/2683. Neighboring Bitwise XOR.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2683. Neighboring Bitwise XOR 5 | // Time Complexity: O(n) 6 | // Space Complexity: O(1) 7 | 8 | func doesValidArrayExist(_ derived: [Int]) -> Bool { 9 | let sum = derived.reduce(0, +) 10 | return sum % 2 == 0 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /2501-3000/2706. Buy Two Chocolates.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2706. Buy Two Chocolates 5 | 6 | // finding smallest two element 7 | // O(N) 8 | 9 | func buyChoco(_ prices: [Int], _ money: Int) -> Int { 10 | var s1 = Int.max 11 | var s2 = Int.max 12 | 13 | for p in prices { 14 | if s1 > p { 15 | s2 = s1 16 | s1 = p 17 | } else if s2 >= p { 18 | s2 = p 19 | } 20 | } 21 | 22 | if s1 + s2 <= money { 23 | return money - (s1 + s2) 24 | } 25 | 26 | return money 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2501-3000/2708. Maximum Strength of a Group.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2708. Maximum Strength of a Group 5 | 6 | func maxStrength(_ nums: [Int]) -> Int { 7 | var prod: Int64 = 1 8 | var largestNegative: Int = Int.min 9 | var largest: Int = Int.min 10 | var negCount: Int = 0 11 | 12 | for n in nums { 13 | if n != 0 { 14 | prod *= Int64(n) 15 | } 16 | if n < 0 { 17 | largestNegative = max(largestNegative, n) 18 | negCount += 1 19 | } 20 | largest = max(largest, n) 21 | } 22 | 23 | if largest == 0 && negCount < 2 { 24 | return 0 25 | } 26 | 27 | if largest < 0 && negCount == 1 { 28 | return largestNegative 29 | } 30 | 31 | if prod > 0 { 32 | return Int(prod) 33 | } 34 | 35 | return Int(prod / Int64(largestNegative)) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /2501-3000/2712. Minimum Cost to Make All Characters Equal.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2712. Minimum Cost to Make All Characters Equal 5 | 6 | func minimumCost(_ s: String) -> Int { 7 | var ans = 0 8 | let n = s.count 9 | let sArray = Array(s) 10 | 11 | for i in 1.. Int { 7 | Set(s).count 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /2501-3000/2717. Semi-Ordered Permutation.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2717. Semi-Ordered Permutation 5 | 6 | func semiOrderedPermutation(_ nums: [Int]) -> Int { 7 | var imin = 0 8 | var imax = nums.count 9 | var n = nums.count 10 | 11 | for i in 0.. Int { 9 | var rowFlag = Array(repeating: true, count: n) 10 | var colFlag = Array(repeating: true, count: n) 11 | var ans: Int64 = 0 12 | var rowRemain = n 13 | var colRemain = n 14 | 15 | for i in (0.. Bool { 7 | let concatenatedString = "\(n)\(2 * n)\(3 * n)" 8 | let uniqueDigits = Set(concatenatedString) 9 | return uniqueDigits.count == 9 && concatenatedString.count == 9 10 | && !uniqueDigits.contains("0") 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /2501-3000/2730. Find the Longest Semi-Repetitive Substring.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2730. Find the Longest Semi-Repetitive Substring 5 | 6 | func longestSemiRepetitiveSubstring(_ s: String) -> Int { 7 | var ans = 1 8 | var i = 0 9 | var j = 1 10 | var last = 0 11 | 12 | let sArray = Array(s) 13 | 14 | while j < sArray.count { 15 | if sArray[j] == sArray[j - 1] { 16 | if last != 0 { 17 | i = last 18 | } 19 | last = j 20 | } 21 | ans = max(ans, j - i + 1) 22 | j += 1 23 | } 24 | 25 | return ans 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2731. Movement of Robots.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2731. Movement of Robots 5 | // O(N logN) 6 | 7 | func sumDistance(_ nums: [Int], _ s: String, _ d: Int) -> Int { 8 | let MOD = 1_000_000_007 9 | var sortedNums = nums 10 | var sIndex = s.startIndex 11 | 12 | for i in 0.. Int { 7 | if nums.count < 3 { 8 | return -1 9 | } 10 | 11 | let a = min(nums[0], nums[1]) 12 | let b = max(nums[0], nums[1]) 13 | let c = nums[2] 14 | 15 | if c < b && c > a { 16 | return c 17 | } 18 | if c < a { 19 | return a 20 | } 21 | if c > b { 22 | return b 23 | } 24 | 25 | return -1 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2734. Lexicographically Smallest String After Substring Operation.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2734. Lexicographically Smallest String After Substring Operation 5 | 6 | func smallestString(_ s: String) -> String { 7 | var characters = Array(s) // Convert to mutable array 8 | var i = 0 9 | while i < characters.count && characters[i] == "a" { 10 | i += 1 11 | } 12 | 13 | if i >= characters.count { 14 | characters[characters.count - 1] = "z" 15 | return String(characters) 16 | } 17 | 18 | while i < characters.count && characters[i] != "a" { 19 | if let asciiValue = characters[i].asciiValue, asciiValue > 97 { 20 | characters[i] = Character(UnicodeScalar(asciiValue - 1)) 21 | } 22 | i += 1 23 | } 24 | 25 | return String(characters) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2735. Collecting Chocolates.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2735. Collecting Chocolates 5 | 6 | // Time complexity: O(n^2) 7 | // Space complexity: O(n) 8 | 9 | func minCost(_ nums: [Int], _ x: Int) -> Int { 10 | let n = nums.count 11 | var res = Array(repeating: 0, count: n) 12 | 13 | for i in 0.. Int { 10 | (mainTank + min((mainTank - 1) / 4, additionalTank)) * 10 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /2501-3000/2740. Find the Value of the Partition.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2740. Find the Value of the Partition 5 | 6 | func findValueOfPartition(_ nums: [Int]) -> Int { 7 | var ans = Int.max 8 | let sortedNums = nums.sorted() 9 | for i in 1.. Int { 9 | let n = cost.count 10 | var dp = [Int](repeating: Int(1e9), count: n + 1) 11 | dp[0] = 0 12 | 13 | for i in 0.. Int { 8 | let mn = min(x, y) 9 | if x == y { 10 | return (4 * x + z * 2) 11 | } else { 12 | return (2 * mn + (mn + 1) * 2 + z * 2) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /2501-3000/2749. Minimum Operations to Make the Integer Zero.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2749. Minimum Operations to Make the Integer Zero 5 | // Time complexity: O(1) 6 | // Space complexity: O(1) 7 | 8 | func makeTheIntegerZero(_ num1: Int, _ num2: Int) -> Int { 9 | for k in 0...60 { 10 | let target = num1 - k * num2 11 | if target >= 0 && target.nonzeroBitCount <= k && k <= target { 12 | return k 13 | } 14 | } 15 | return -1 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /2501-3000/2760. Longest Even Odd Subarray With Threshold.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2760. Longest Even Odd Subarray With Threshold 5 | // Sliding window 6 | 7 | func longestAlternatingSubarray(_ nums: [Int], _ threshold: Int) -> Int { 8 | var ans = 0 9 | var i = 0 10 | var last = Int.max 11 | 12 | while i < nums.count { 13 | if nums[i] > threshold || (i > 0 && (nums[i] % 2) == (nums[i - 1] % 2)) { 14 | ans = max(ans, i - last) 15 | last = Int.max 16 | } 17 | if last == Int.max && nums[i] <= threshold && nums[i] % 2 == 0 { 18 | last = i 19 | } 20 | i += 1 21 | } 22 | ans = max(ans, i - last) 23 | return ans 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /2501-3000/2761. Prime Pairs With Target Sum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2761. Prime Pairs With Target Sum 5 | 6 | func sieveOfEratosthenes(_ n: Int) -> [Bool] { 7 | var isPrime = [Bool](repeating: true, count: n + 1) 8 | isPrime[0] = false 9 | isPrime[1] = false 10 | 11 | var i = 2 12 | while i * i <= n { 13 | if isPrime[i] { 14 | var j = i * i 15 | while j <= n { 16 | isPrime[j] = false 17 | j += i 18 | } 19 | } 20 | i += 1 21 | } 22 | 23 | return isPrime 24 | } 25 | 26 | func findPrimePairs(_ n: Int) -> [[Int]] { 27 | var ans = [[Int]]() 28 | if n == 1 { 29 | return ans 30 | } 31 | 32 | let primes = sieveOfEratosthenes(n) 33 | 34 | for i in 1...(n / 2) { 35 | if primes[i] && primes[n - i] { 36 | ans.append([i, n - i]) 37 | } 38 | } 39 | 40 | return ans 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /2501-3000/2763. Sum of Imbalance Numbers of All Subarrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2763. Sum of Imbalance Numbers of All Subarrays 5 | 6 | // Time complexity: O(n^2) 7 | // Space complexity: O(n) 8 | 9 | func sumImbalanceNumbers(_ nums: [Int]) -> Int { 10 | var res = 0 11 | let n = nums.count 12 | 13 | for i in 0..() 15 | s.insert(nums[i]) 16 | var cur = 0 17 | 18 | for j in (i + 1).. Int { 10 | let n = nums.count 11 | var res = 0 12 | 13 | for i in 0.. 1 ? res : -1 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /2501-3000/2766. Relocate Marbles.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2766. Relocate Marbles 5 | 6 | func relocateMarbles(_ nums: [Int], _ moveFrom: [Int], _ moveTo: [Int]) -> [Int] { 7 | var s = Set(nums) 8 | for (from, to) in zip(moveFrom, moveTo) { 9 | s.remove(from) 10 | s.insert(to) 11 | } 12 | return s.sorted() 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /2501-3000/2767. Partition String Into Minimum Beautiful Substrings.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2767. Partition String Into Minimum Beautiful Substrings 5 | 6 | // Time complexity: O(n^2) 7 | // Space complexity: O(n) 8 | 9 | func minimumBeautifulSubstrings(_ s: String) -> Int { 10 | let n = s.count 11 | var dp = [Int](repeating: n + 1, count: n + 1) 12 | dp[0] = 0 13 | 14 | for (i, char) in s.enumerated() { 15 | if char == "0" { continue } 16 | var cur = 0 17 | var index = i 18 | while index < n { 19 | cur = cur * 2 + Int(String(s[s.index(s.startIndex, offsetBy: index)]))! 20 | if 15625 % cur == 0 { 21 | dp[index + 1] = min(dp[index + 1], dp[i] + 1) 22 | } 23 | index += 1 24 | } 25 | } 26 | 27 | return dp[n] > n ? -1 : dp[n] 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2768. Number of Black Blocks.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2768. Number of Black Blocks 5 | 6 | func countBlackBlocks(_ m: Int, _ n: Int, _ coordinates: [[Int]]) -> [Int] { 7 | var mp = [Int: Int]() 8 | 9 | for c in coordinates { 10 | if c[0] < m - 1 && c[1] < n - 1 { mp[c[1] * 1_000_000 + c[0], default: 0] += 1 } 11 | if c[0] - 1 >= 0 && c[1] < n - 1 { mp[c[1] * 1_000_000 + c[0] - 1, default: 0] += 1 } 12 | if c[1] - 1 >= 0 && c[0] < m - 1 { mp[(c[1] - 1) * 1_000_000 + c[0], default: 0] += 1 } 13 | if c[0] - 1 >= 0 && c[1] - 1 >= 0 { 14 | mp[(c[1] - 1) * 1_000_000 + c[0] - 1, default: 0] += 1 15 | } 16 | } 17 | 18 | var ans = [Int](repeating: 0, count: 5) 19 | for (_, count) in mp { ans[count] += 1 } 20 | 21 | ans[0] = (m - 1) * (n - 1) 22 | ans[0] -= ans[1] + ans[2] + ans[3] + ans[4] 23 | 24 | return ans 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /2501-3000/2769. Find the Maximum Achievable Number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2769. Find the Maximum Achievable Number 5 | 6 | func theMaximumAchievableX(_ num: Int, _ t: Int) -> Int { 7 | num + 2 * t 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /2501-3000/2770. Maximum Number of Jumps to Reach the Last Index.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2770. Maximum Number of Jumps to Reach the Last Index 5 | // Memoized 6 | 7 | func maximumJumps(_ nums: [Int], _ target: Int) -> Int { 8 | func find(_ ind: Int, _ nums: [Int], _ tar: Int, _ dp: inout [Int]) -> Int { 9 | if ind == nums.count - 1 { 10 | return 0 11 | } 12 | 13 | if dp[ind] != -1 { 14 | return dp[ind] 15 | } 16 | 17 | var ans = Int.min 18 | 19 | for i in (ind + 1).. 0 ? ans : -1 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /2501-3000/2771. Longest Non-decreasing Subarray From Two Arrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2771. Longest Non-decreasing Subarray From Two Arrays 5 | 6 | // Time complexity: O(n) 7 | // Space complexity: O(1) 8 | 9 | func maxNonDecreasingLength(_ nums1: [Int], _ nums2: [Int]) -> Int { 10 | var res = 1 11 | var dp1 = 1 12 | var dp2 = 1 13 | let n = nums1.count 14 | 15 | for i in 1.. Bool { 10 | var nums = nums // Make a mutable copy of the input array 11 | var cur = 0 12 | let n = nums.count 13 | 14 | for i in 0.. nums[i] { 16 | return false 17 | } 18 | nums[i] -= cur 19 | cur += nums[i] 20 | if i >= k - 1 { 21 | cur -= nums[i - k + 1] 22 | } 23 | } 24 | 25 | return cur == 0 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2778. Sum of Squares of Special Elements.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2778. Sum of Squares of Special Elements 5 | 6 | func sumOfSquares(_ nums: [Int]) -> Int { 7 | var sum = 0 8 | let n = nums.count 9 | 10 | for i in 0.. Int { 7 | let sortedNums = nums.sorted() 8 | var start = 0 9 | var ans = 0 10 | 11 | for i in 0.. 2 * k { 14 | start += 1 15 | } 16 | // the current window i.e. [start ... i] is valid, so consider it 17 | ans = max(ans, i - start + 1) 18 | } 19 | 20 | return ans 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /2501-3000/2781. Length of the Longest Valid Substring.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2781. Length of the Longest Valid Substring 5 | 6 | func longestValidSubstring(_ word: String, _ forbidden: [String]) -> Int { 7 | let forbiddenSet = Set(forbidden) 8 | var res = 0 9 | var right = word.count - 1 10 | let wordArray = Array(word) 11 | 12 | for left in stride(from: word.count - 1, through: 0, by: -1) { 13 | for k in left...min(left + 9, right) { 14 | let substring = String(wordArray[left...k]) 15 | if forbiddenSet.contains(substring) { 16 | right = k - 1 17 | break 18 | } 19 | } 20 | res = max(res, right - left + 1) 21 | } 22 | 23 | return res 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /2501-3000/2784. Check if Array is Good.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2784. Check if Array is Good 5 | 6 | // Time complexity: O(n) 7 | // Space complexity: O(1) 8 | 9 | func isGood(_ nums: [Int]) -> Bool { 10 | var nums = nums 11 | let sz = nums.count 12 | 13 | var i = 0 14 | while i < sz { 15 | if nums[i] >= sz { 16 | return false 17 | } 18 | 19 | let pos = nums[i] - 1 20 | if nums[pos] == nums[i] { 21 | i += 1 22 | } else { 23 | nums.swapAt(pos, i) 24 | } 25 | } 26 | 27 | for i in 0..= 2 && nums.last == sz - 1 && nums[sz - 2] == sz - 1 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /2501-3000/2785. Sort Vowels in a String.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2785. Sort Vowels in a String 5 | 6 | // Time complexity: O(n*logn) 7 | // Space complexity: O(n) 8 | 9 | func sortVowels(_ s: String) -> String { 10 | var vow = [Character]() 11 | var pos = [Int]() 12 | 13 | for (index, char) in s.enumerated() { 14 | let lowerChar = char.lowercased() 15 | if lowerChar == "a" || lowerChar == "e" || lowerChar == "i" || lowerChar == "o" 16 | || lowerChar == "u" 17 | { 18 | vow.append(char) 19 | pos.append(index) 20 | } 21 | } 22 | 23 | vow.sort() 24 | 25 | var answer = Array(s) 26 | for (i, index) in pos.enumerated() { 27 | answer[index] = vow[i] 28 | } 29 | 30 | return String(answer) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /2501-3000/2786. Visit Array Positions to Maximize Score.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2786. Visit Array Positions to Maximize Score 5 | 6 | func maxScore(_ nums: [Int], _ x: Int) -> Int { 7 | var eve = nums[0] - (nums[0] % 2 == 1 ? x : 0) 8 | var odd = nums[0] - (nums[0] % 2 == 1 ? 0 : x) 9 | 10 | for i in 1.. Int { 10 | if n < 0 { 11 | return 0 12 | } 13 | if n == 0 { 14 | return 1 15 | } 16 | if Int(pow(Double(num), Double(x))) > n { 17 | return 0 18 | } 19 | if dp[n][num] != -1 { 20 | return dp[n][num] 21 | } 22 | 23 | let temp = Int(pow(Double(num), Double(x))) 24 | 25 | let pick = f(n - temp, num + 1, x) % mod 26 | let skip = f(n, num + 1, x) % mod 27 | 28 | dp[n][num] = (skip + pick) % mod 29 | return dp[n][num] 30 | } 31 | 32 | func numberOfWays(_ n: Int, _ x: Int) -> Int { 33 | return f(n, 1, x) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /2501-3000/2788. Split Strings by Separator.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2788. Split Strings by Separator 5 | 6 | // Time complexity: O(n∗k) where k is length of each array index 7 | // Space complexity: O(k) 8 | 9 | func splitWordsBySeparator(_ words: [String], _ separator: Character) -> [String] { 10 | var result = [String]() 11 | 12 | for word in words { 13 | let components = word.split(separator: separator) 14 | for component in components { 15 | if !component.isEmpty { 16 | result.append(String(component)) 17 | } 18 | } 19 | } 20 | 21 | return result 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /2501-3000/2789. Largest Element in an Array after Merge Operations.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2789. Largest Element in an Array after Merge Operations 5 | 6 | // Time complexity: O(N) 7 | // Space complexity: O(1) 8 | 9 | func maxArrayValue(_ nums: [Int]) -> Int { 10 | var ans = nums[nums.count - 1] 11 | var sum = nums[nums.count - 1] 12 | 13 | for i in stride(from: nums.count - 2, through: 0, by: -1) { 14 | if nums[i] <= sum { 15 | sum += nums[i] 16 | } else { 17 | sum = nums[i] 18 | } 19 | 20 | ans = max(ans, sum) 21 | } 22 | 23 | return ans 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /2501-3000/2798. Number of Employees Who Met the Target.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2798. Number of Employees Who Met the Target 5 | 6 | func numberOfEmployeesWhoMetTarget(_ hours: [Int], _ target: Int) -> Int { 7 | var count = 0 8 | for h in hours { 9 | if h >= target { 10 | count += 1 11 | } 12 | } 13 | return count 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /2501-3000/2799. Count Complete Subarrays in an Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2799. Count Complete Subarrays in an Array 5 | 6 | func countCompleteSubarrays(_ nums: [Int]) -> Int { 7 | var mp = [Int: Int]() 8 | var all = [Int: Int]() 9 | 10 | for n in nums { 11 | all[n, default: 0] += 1 12 | } 13 | 14 | var front = 0 15 | var back = 0 16 | var ans = 0 17 | 18 | while front < nums.count { 19 | mp[nums[front], default: 0] += 1 20 | 21 | while back <= front && mp.count == all.count { 22 | if let count = mp[nums[back]] { 23 | if count - 1 == 0 { 24 | mp[nums[back]] = nil 25 | } else { 26 | mp[nums[back]] = count - 1 27 | } 28 | } 29 | back += 1 30 | ans += (nums.count - front) 31 | } 32 | 33 | front += 1 34 | } 35 | 36 | return ans 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /2501-3000/2806. Account Balance After Rounded Purchase.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2806. Account Balance After Rounded Purchase 5 | 6 | func accountBalanceAfterPurchase(_ purchaseAmount: Int) -> Int { 7 | return 100 - ((purchaseAmount + 5) / 10) * 10 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /2501-3000/2808. Minimum Seconds to Equalize a Circular Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2808. Minimum Seconds to Equalize a Circular Array 5 | 6 | func minimumSeconds(_ nums: [Int]) -> Int { 7 | var nPos: [Int: [Int]] = [:] 8 | for (i, num) in nums.enumerated() { 9 | nPos[num, default: []].append(i) 10 | } 11 | 12 | var result = Int.max 13 | for (_, pos) in nPos { 14 | var updatedPos = pos 15 | updatedPos.append(pos[0] + nums.count) 16 | var seconds = 0 17 | for i in 1.. String { 8 | var dq = [Character]() 9 | var flip = false 10 | 11 | for ch in s { 12 | if ch == "i" { 13 | flip = !flip 14 | } else { 15 | if flip { 16 | dq.insert(ch, at: dq.startIndex) 17 | } else { 18 | dq.append(ch) 19 | } 20 | } 21 | } 22 | 23 | return flip ? String(dq.reversed()) : String(dq) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /2501-3000/2811. Check if it is Possible to Split Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2811. Check if it is Possible to Split Array 5 | // O(n) 6 | 7 | func canSplitArray(_ nums: [Int], _ m: Int) -> Bool { 8 | if nums.count <= 2 { 9 | return true 10 | } 11 | 12 | for i in 1..= m { 14 | return true 15 | } 16 | } 17 | 18 | return false 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2824. Count Pairs Whose Sum is Less than Target.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2824. Count Pairs Whose Sum is Less than Target 5 | // Two Pointers 6 | 7 | // Time complexity: O(n log n) 8 | // Space complexity: O(1) 9 | 10 | func countPairs(_ nums: [Int], _ target: Int) -> Int { 11 | var count = 0 12 | var left = 0 13 | var right = nums.count - 1 14 | 15 | let sortedNums = nums.sorted() 16 | 17 | while left < right { 18 | if sortedNums[left] + sortedNums[right] < target { 19 | count += right - left 20 | left += 1 21 | } else { 22 | right -= 1 23 | } 24 | } 25 | 26 | return count 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2501-3000/2825. Make String a Subsequence Using Cyclic Increments.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2825. Make String a Subsequence Using Cyclic Increments 5 | 6 | func canMakeSubsequence(_ str1: String, _ str2: String) -> Bool { 7 | var i = 0 8 | let str1Array = Array(str1) 9 | 10 | for c in str2 { 11 | let t: Character = 12 | (c == "a") 13 | ? "z" : Character(UnicodeScalar(String(c).unicodeScalars.first!.value - 1)!) 14 | 15 | while i < str1Array.count && (str1Array[i] != c && str1Array[i] != t) { 16 | i += 1 17 | } 18 | 19 | if i >= str1Array.count { 20 | return false 21 | } 22 | 23 | i += 1 24 | } 25 | 26 | return true 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2501-3000/2826. Sorting Three Groups.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2826. Sorting Three Groups 5 | 6 | // Time complexity: O(kn) 7 | // Space complexity: O(k) 8 | 9 | func minimumOperations(_ nums: [Int]) -> Int { 10 | var dp = [Int](repeating: nums.count, count: 4) 11 | 12 | for a in nums { 13 | dp[a] -= 1 14 | dp[2] = min(dp[2], dp[1]) 15 | dp[3] = min(dp[3], dp[2]) 16 | } 17 | 18 | return dp[3] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2827. Number of Beautiful Integers in the Range.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2827. Number of Beautiful Integers in the Range 5 | 6 | func check(_ num: Int) -> Int { 7 | var even = 0 8 | var odd = 0 9 | var n = num 10 | 11 | while n > 0 { 12 | if n % 2 == 0 { 13 | even += 1 14 | } else { 15 | odd += 1 16 | } 17 | 18 | n /= 10 19 | } 20 | 21 | return even == odd ? 1 : 0 22 | } 23 | 24 | func numberOfBeautifulIntegers(_ low: Int, _ high: Int, _ k: Int) -> Int { 25 | var low = ((low - 1) / k + 1) * k 26 | var count = 0 27 | while low <= high { 28 | count += check(low) 29 | low += k 30 | 31 | if low >= 100_000_000 { 32 | return count 33 | } 34 | } 35 | 36 | return count 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /2501-3000/2828. Check if a String Is an Acronym of Words.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2828. Check if a String Is an Acronym of Words 5 | 6 | func isAcronym(_ words: [String], _ s: String) -> Bool { 7 | var acronym = "" 8 | 9 | for word in words { 10 | if !word.isEmpty { 11 | acronym.append(word.first!) 12 | } 13 | } 14 | 15 | return acronym == s 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /2501-3000/2829. Determine the Minimum Sum of a k-avoiding Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2829. Determine the Minimum Sum of a k-avoiding Array 5 | 6 | // Time complexity: O(1) 7 | // Space complexity: O(1) 8 | 9 | func minimumSum(_ n: Int, _ k: Int) -> Int { 10 | // Function to calculate the sum of integers from 1 to `count`. 11 | func calculateSumInRange(start: Int, count: Int) -> Int { 12 | return (count * (2 * start + (count - 1))) / 2 13 | } 14 | 15 | let middle = k / 2 16 | 17 | if n <= middle { 18 | // If n is less than or equal to middle, we can simply sum the first n positive integers. 19 | return n * (n + 1) / 2 20 | } 21 | 22 | let leftSum = middle * (middle + 1) / 2 23 | 24 | let remainingNumbers = n - middle 25 | 26 | return leftSum + calculateSumInRange(start: k, count: remainingNumbers) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2501-3000/2831. Find the Longest Equal Subarray.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2831. Find the Longest Equal Subarray 5 | 6 | // Time complexity: O(n + n) 7 | // Space complexity: O(n) 8 | 9 | func longestEqualSubarray(_ nums: [Int], _ k: Int) -> Int { 10 | var i = 0 11 | var j = 0 12 | var m = [Int: Int]() 13 | var ans = 1 14 | var mf = 0 15 | 16 | while j < nums.count { 17 | let current = nums[j] 18 | m[current, default: 0] += 1 19 | mf = max(mf, m[current]!) 20 | 21 | var rem = j - i + 1 - mf 22 | 23 | while i < nums.count && rem > k { 24 | let removed = nums[i] 25 | m[removed]! -= 1 26 | i += 1 27 | mf = max(mf, m[current]!) 28 | rem = j - i + 1 - mf 29 | } 30 | 31 | ans = max(ans, mf) 32 | j += 1 33 | } 34 | 35 | return ans 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /2501-3000/2833. Furthest Point From Origin.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2833. Furthest Point From Origin 5 | 6 | func furthestDistanceFromOrigin(_ moves: String) -> Int { 7 | var Ls = 0 8 | var Rs = 0 9 | var Bs = 0 10 | 11 | for move in moves { 12 | if move == "L" { 13 | Ls += 1 14 | } else if move == "R" { 15 | Rs += 1 16 | } else { 17 | Bs += 1 18 | } 19 | } 20 | 21 | return abs(Ls - Rs) + Bs 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /2501-3000/2840. Check if Strings Can be Made Equal With Operations II.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2840. Check if Strings Can be Made Equal With Operations II 5 | 6 | func checkStrings(_ s1: String, _ s2: String) -> Bool { 7 | let even1 = s1.enumerated().compactMap { $0.offset % 2 == 0 ? $0.element : nil } 8 | let even2 = s2.enumerated().compactMap { $0.offset % 2 == 0 ? $0.element : nil } 9 | let odd1 = s1.enumerated().compactMap { $0.offset % 2 != 0 ? $0.element : nil } 10 | let odd2 = s2.enumerated().compactMap { $0.offset % 2 != 0 ? $0.element : nil } 11 | 12 | return odd1.sorted() == odd2.sorted() && even1.sorted() == even2.sorted() 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /2501-3000/2844. Minimum Operations to Make a Special Number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2844. Minimum Operations to Make a Special Number 5 | 6 | func minimumOperations(_ num: String) -> Int { 7 | let n = num.count 8 | var ans = n 9 | 10 | for i in stride(from: n - 1, through: 0, by: -1) { 11 | for j in stride(from: i - 1, through: 0, by: -1) { 12 | let digitI = Int(String(num[num.index(num.startIndex, offsetBy: i)])) ?? 0 13 | let digitJ = Int(String(num[num.index(num.startIndex, offsetBy: j)])) ?? 0 14 | let t = digitI + digitJ * 10 15 | if t % 25 == 0 { 16 | ans = min(ans, n - j - 2) 17 | } 18 | } 19 | if num[num.index(num.startIndex, offsetBy: i)] == "0" { 20 | ans = min(ans, n - 1) 21 | } 22 | } 23 | 24 | return ans 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /2501-3000/2845. Count of Interesting Subarrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2845. Count of Interesting Subarrays 5 | 6 | // Time complexity: O(n) 7 | // Space complexity: O(n) 8 | 9 | func countInterestingSubarrays(_ nums: [Int], _ modulo: Int, _ k: Int) -> Int { 10 | let n = nums.count 11 | var arr = [Int](repeating: 0, count: n + 1) 12 | var nm = [Int: Int]() 13 | arr[0] = 0 14 | nm[0] = 1 15 | var ans = 0 16 | 17 | for i in 0.. Int { 7 | var pref = Array(repeating: 0, count: 200) 8 | 9 | for num in nums { 10 | pref[num[0]] += 1 11 | pref[num[1] + 1] -= 1 12 | } 13 | 14 | for indx in 1.. Bool { 7 | let xdiff = abs(sx - fx) 8 | let ydiff = abs(sy - fy) 9 | 10 | if xdiff == 0 && ydiff == 0 && t == 1 { 11 | return false 12 | } 13 | 14 | return (min(xdiff, ydiff) + abs(xdiff - ydiff)) <= t 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /2501-3000/2856. Minimum Array Length After Pair Removals.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2856. Minimum Array Length After Pair Removals 5 | 6 | // Time complexity: O(n) 7 | // Space complexity: O(n) 8 | 9 | func minLengthAfterRemovals(_ nums: [Int]) -> Int { 10 | var mp = [Int: Int]() 11 | for i in nums { 12 | mp[i, default: 0] += 1 13 | } 14 | 15 | var maxi = 0 16 | for (_, count) in mp { 17 | maxi = max(maxi, count) 18 | } 19 | 20 | let n = nums.count 21 | if maxi <= n / 2 { 22 | if n % 2 == 1 { 23 | return 1 24 | } else { 25 | return 0 26 | } 27 | } 28 | 29 | return 2 * maxi - n 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /2501-3000/2857. Count Pairs of Points With Distance k.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2857. Count Pairs of Points With Distance k 5 | // O(n) 6 | 7 | func countPairs(_ coordinates: [[Int]], _ k: Int) -> Int { 8 | var result = 0 9 | var seen = [String: Int]() 10 | 11 | for point in coordinates { 12 | let x = point[0] 13 | let y = point[1] 14 | 15 | for split in 0...k { 16 | let xComplement = x ^ split 17 | let yComplement = y ^ (k - split) 18 | 19 | let key = "\(xComplement),\(yComplement)" 20 | result += seen[key] ?? 0 21 | } 22 | 23 | let key = "\(x),\(y)" 24 | seen[key] = (seen[key] ?? 0) + 1 25 | } 26 | 27 | return result 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2859. Sum of Values at Indices With K Set Bits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2859. Sum of Values at Indices With K Set Bits 5 | 6 | // Time complexity: O(n * log n) 7 | // Space complexity: O(1) 8 | 9 | func sumIndicesWithKSetBits(_ nums: [Int], _ k: Int) -> Int { 10 | // Function to count the set bits in a number 11 | func getBitCount(_ number: Int) -> Int { 12 | var bitCount = 0 13 | var num = number 14 | while num > 0 { 15 | if num % 2 == 1 { 16 | bitCount += 1 17 | } 18 | num = num >> 1 19 | } 20 | return bitCount 21 | } 22 | 23 | var sum = 0 24 | for i in 0.. Int { 7 | let sortedNums = nums.sorted() 8 | var ways = sortedNums[0] == 0 ? 0 : 1 9 | 10 | for i in 0.. sortedNums[i] 14 | && (i + 1 == sortedNums.count || countWith < sortedNums[i + 1]) 15 | { 16 | ways += 1 17 | } 18 | } 19 | 20 | return ways 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /2501-3000/2864. Maximum Odd Binary Number.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2864. Maximum Odd Binary Number 5 | // O(n) 6 | 7 | func maximumOddBinaryNumber(_ s: String) -> String { 8 | let n = s.count 9 | var cnt = 0 10 | var str = "" 11 | 12 | for char in s { 13 | if char == "1" { 14 | cnt += 1 15 | } 16 | str += "0" 17 | } 18 | 19 | let t = cnt - 1 20 | 21 | for _ in 0.. Int { 7 | let n = maxHeights.count 8 | var ans = 0 9 | 10 | for i in 0.. ans { 29 | ans = sum 30 | } 31 | } 32 | 33 | return ans 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /2501-3000/2869. Minimum Operations to Collect Elements.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2869. Minimum Operations to Collect Elements 5 | 6 | func minOperations(_ nums: [Int], _ k: Int) -> Int { 7 | var st = Set() 8 | var i = nums.count - 1 9 | while st.count < k { 10 | if nums[i] <= k { 11 | st.insert(nums[i]) 12 | } 13 | i -= 1 14 | } 15 | return nums.count - i - 1 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /2501-3000/2870. Minimum Number of Operations to Make Array Empty.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2870. Minimum Number of Operations to Make Array Empty 5 | 6 | func minOperations(_ nums: [Int]) -> Int { 7 | var countDict = [Int: Int]() 8 | 9 | // Count the occurrences of each element 10 | for num in nums { 11 | countDict[num, default: 0] += 1 12 | } 13 | 14 | // Check if there's any element with a count of 1 15 | if countDict.values.min() == 1 { 16 | return -1 17 | } 18 | 19 | var totalOperations = 0 20 | for count in countDict.values { 21 | // Calculate the operations needed for each count 22 | totalOperations += count / 3 + (count % 3 > 0 ? 1 : 0) 23 | } 24 | 25 | return totalOperations 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2871. Split Array Into Maximum Number of Subarrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2871. Split Array Into Maximum Number of Subarrays 5 | 6 | func maxSubarrays(_ nums: [Int]) -> Int { 7 | var res = 0 8 | var cur = 0 9 | 10 | for n in nums { 11 | cur = cur == 0 ? n : cur & n 12 | res += cur == 0 ? 1 : 0 13 | } 14 | 15 | return max(1, res) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /2501-3000/2873. Maximum Value of an Ordered Triplet I.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2873. Maximum Value of an Ordered Triplet I 5 | 6 | // For each element 'a' in the array 'A', we compute and update the following values: 7 | // 'res' represents the maximum value of a triplet (A[i] - A[j]) * A[k]. 8 | // 'maxab' represents the maximum difference between pairs of elements A[i] - A[j]. 9 | // 'maxa' represents the maximum element value among A[i]. 10 | 11 | // Time complexity: O(n) 12 | // Space complexity: O(1) 13 | 14 | func maximumTripletValue(_ nums: [Int]) -> Int { 15 | var res = 0 16 | var maxa = 0 17 | var maxab = 0 18 | 19 | for a in nums { 20 | res = max(res, maxab * a) 21 | maxab = max(maxab, maxa - a) 22 | maxa = max(maxa, a) 23 | } 24 | 25 | return res 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2874. Maximum Value of an Ordered Triplet II.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2874. Maximum Value of an Ordered Triplet II 5 | 6 | // For every element 'a' in the array 'A', we keep track of three values: 7 | // 'res' represents the maximum value of a triplet (A[i] - A[j]) * A[k]. 8 | // 'maxab' is the maximum value of the pair A[i] - A[j]. 9 | // 'maxa' is the maximum value among all elements in the array A[i]. 10 | // We continuously update these values as we iterate through the array to find the maximum triplet value. 11 | 12 | // Time complexity: O(n) 13 | // Space complexity: O(1) 14 | 15 | func maximumTripletValue(_ nums: [Int]) -> Int { 16 | var res: Int64 = 0 17 | var maxa: Int64 = 0 18 | var maxab: Int64 = 0 19 | 20 | for a in nums { 21 | res = max(res, maxab * Int64(a)) 22 | maxab = max(maxab, maxa - Int64(a)) 23 | maxa = max(maxa, Int64(a)) 24 | } 25 | 26 | return Int(res) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2501-3000/2875. Minimum Size Subarray in Infinite Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2875. Minimum Size Subarray in Infinite Array 5 | 6 | // Time complexity: O(n) 7 | // Space complexity: O(n) 8 | 9 | func minSizeSubarray(_ nums: [Int], _ target: Int) -> Int { 10 | let sumA = nums.reduce(0, +) 11 | let n = nums.count 12 | var k = target / sumA 13 | var res = n 14 | var target = target % sumA 15 | 16 | if target == 0 { 17 | return k * n 18 | } 19 | 20 | var dp: [Int: Int] = [0: -1] 21 | var su = 0 22 | 23 | for i in 0..<(2 * n) { 24 | su += nums[i % n] 25 | if let prevIndex = dp[su - target] { 26 | res = min(res, i - prevIndex) 27 | } 28 | dp[su] = i 29 | } 30 | 31 | return res < n ? res + k * n : -1 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /2501-3000/2894. Divisible and Non-divisible Sums Difference.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2894. Divisible and Non-divisible Sums Difference 5 | 6 | // Time Complexity: O(n1) 7 | // Space Complexity: O(n) 8 | 9 | func differenceOfSums(_ n: Int, _ m: Int) -> Int { 10 | let sum1 = (1 + n) * n / 2 11 | let sum2 = (1 + n / m) * (n / m) * m 12 | return sum1 - sum2 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /2501-3000/2895. Minimum Processing Time.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2895. Minimum Processing Time 5 | 6 | func minProcessingTime(_ processorTime: [Int], _ tasks: [Int]) -> Int { 7 | var sortedProcessorTime = processorTime.sorted() 8 | var sortedTasks = tasks.sorted(by: >) 9 | var time = 0 10 | 11 | for i in 0.. Int { 10 | var count = [Int](repeating: 0, count: 32) 11 | var res: Int64 = 0 12 | let mod: Int64 = 1_000_000_007 13 | 14 | for a in nums { 15 | for i in 0..<32 { 16 | if (a & (1 << i)) != 0 { 17 | count[i] += 1 18 | } 19 | } 20 | } 21 | 22 | for _ in 0.. 0 { 26 | count[i] -= 1 27 | cur += Int64(1 << i) 28 | } 29 | } 30 | res = (res + cur * cur % mod) % mod 31 | } 32 | 33 | return Int(res) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /2501-3000/2899. Last Visited Integers.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2899. Last Visited Integers 5 | 6 | func lastVisitedIntegers(_ words: [String]) -> [Int] { 7 | var v: [Int] = [] 8 | var ans: [Int] = [] 9 | var count = 0 10 | 11 | for word in words { 12 | if word == "prev" { 13 | count += 1 14 | if count > v.count { 15 | ans.append(-1) 16 | } else { 17 | ans.append(v[v.count - count]) 18 | } 19 | } else { 20 | count = 0 21 | v.append(Int(word)!) 22 | } 23 | } 24 | return ans 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /2501-3000/2900. Longest Unequal Adjacent Groups Subsequence I.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2900. Longest Unequal Adjacent Groups Subsequence I 5 | 6 | func getWordsInLongestSubsequence(_ n: Int, _ words: [String], _ groups: [Int]) -> [String] { 7 | var ans: [String] = [] 8 | var last = groups[0] 9 | ans.append(words[0]) 10 | 11 | for i in 1.. [Int] { 7 | // If both differences are zero, return any pair of indices 8 | if indexDifference == 0 && valueDifference == 0 { 9 | return [0, 0] 10 | } 11 | 12 | // Create an array of all pairs of indices that satisfy the index difference condition 13 | let pairs = nums.indices 14 | .flatMap { i in nums.indices.map { j in (i, j) } } 15 | .filter { abs($0.0 - $0.1) >= indexDifference } 16 | 17 | // Loop through the pairs and check the value difference condition 18 | for (i, j) in pairs { 19 | if abs(nums[i] - nums[j]) >= valueDifference { 20 | return [i, j] 21 | } 22 | } 23 | 24 | // If no pair satisfies both conditions, return [-1, -1] 25 | return [-1, -1] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2905. Find Indices With Index and Value Difference II.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2905. Find Indices With Index and Value Difference II 5 | 6 | // Time complexity: O(N) 7 | // Space complexity: O(1) 8 | 9 | func findIndices(_ nums: [Int], _ indexDifference: Int, _ valueDifference: Int) -> [Int] { 10 | var minIndex = 0 11 | var maxIndex = 0 12 | 13 | for i in stride(from: indexDifference, to: nums.count, by: 1) { 14 | if nums[i - indexDifference] < nums[minIndex] { 15 | minIndex = i - indexDifference 16 | } 17 | if nums[i - indexDifference] > nums[maxIndex] { 18 | maxIndex = i - indexDifference 19 | } 20 | 21 | if abs(nums[i] - nums[minIndex]) >= valueDifference { 22 | return [minIndex, i] 23 | } 24 | if abs(nums[i] - nums[maxIndex]) >= valueDifference { 25 | return [maxIndex, i] 26 | } 27 | } 28 | 29 | return [-1, -1] 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /2501-3000/2908. Minimum Sum of Mountain Triplets I.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2908. Minimum Sum of Mountain Triplets I 5 | 6 | func minimumSum(_ nums: [Int]) -> Int { 7 | let n = nums.count 8 | 9 | var leftMin = [Int](repeating: 0, count: n) 10 | leftMin[0] = nums[0] 11 | for i in 1.. leftMin[i - 1] && nums[i] > rightMin[i + 1] { 25 | ans = min(ans, leftMin[i - 1] + nums[i] + rightMin[i + 1]) 26 | } 27 | } 28 | 29 | return ans == Int.max ? -1 : ans 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /2501-3000/2909. Minimum Sum of Mountain Triplets II.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2909. Minimum Sum of Mountain Triplets II 5 | 6 | func minimumSum(_ nums: [Int]) -> Int { 7 | var smallestRight = Array(repeating: nums.last!, count: nums.count) 8 | 9 | for i in stride(from: nums.count - 2, through: 0, by: -1) { 10 | smallestRight[i] = min(smallestRight[i + 1], nums[i]) 11 | } 12 | 13 | var smallestLeft = nums[0] 14 | var ans = -1 15 | 16 | for i in 1.. Int { 7 | var ans = 0 8 | var count = 0 9 | 10 | for i in 0.. Int { 7 | var ans = 0 8 | var lastSeen = s.first! 9 | var count = 0 10 | 11 | for c in s { 12 | if c == lastSeen { 13 | count += 1 14 | } else { 15 | if count % 2 != 0 { 16 | ans += 1 17 | count = 0 18 | } else { 19 | count = 1 20 | } 21 | lastSeen = c 22 | } 23 | } 24 | 25 | return ans 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2915. Length of the Longest Subsequence That Sums to Target.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2915. Length of the Longest Subsequence That Sums to Target 5 | 6 | var dp: [[Int]] = [] 7 | 8 | func solve(_ nums: [Int], _ i: Int, _ target: Int) -> Int { 9 | if target == 0 { 10 | return 0 11 | } 12 | if target < 0 || i >= nums.count { 13 | return -1001 14 | } 15 | if dp[i][target] != -1 { 16 | return dp[i][target] 17 | } 18 | let take = 1 + solve(nums, i + 1, target - nums[i]) 19 | let notTake = solve(nums, i + 1, target) 20 | dp[i][target] = max(take, notTake) 21 | return dp[i][target] 22 | } 23 | 24 | func lengthOfLongestSubsequence(_ nums: [Int], _ target: Int) -> Int { 25 | dp = Array(repeating: Array(repeating: -1, count: 1001), count: 1001) 26 | let ans = solve(nums, 0, target) 27 | return (ans > 0) ? ans : -1 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2917. Find the K-or of an Array.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2917. Find the K-or of an Array 5 | 6 | func findKOr(_ nums: [Int], _ k: Int) -> Int { 7 | var dp = [Int](repeating: 0, count: 31) 8 | 9 | for num in nums { 10 | var i = 0 11 | var numCopy = num 12 | 13 | while numCopy > 0 { 14 | if numCopy & 1 == 1 { 15 | dp[i] += 1 16 | } 17 | i += 1 18 | numCopy = numCopy >> 1 19 | } 20 | } 21 | 22 | var ans = 0 23 | var bit = 1 24 | 25 | for i in 0..<31 { 26 | if dp[i] >= k { 27 | ans |= bit 28 | } 29 | bit <<= 1 30 | } 31 | 32 | return ans 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /2501-3000/2918. Minimum Equal Sum of Two Arrays After Replacing Zeros.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros 5 | // Greedy 6 | 7 | func minSum(_ nums1: [Int], _ nums2: [Int]) -> Int { 8 | var s1 = 0 9 | var s2 = 0 10 | var c1 = 0 11 | var c2 = 0 12 | 13 | for val in nums1 { 14 | s1 += val 15 | c1 += (val == 0) ? 1 : 0 16 | } 17 | 18 | for val in nums2 { 19 | s2 += val 20 | c2 += (val == 0) ? 1 : 0 21 | } 22 | 23 | if c1 == 0 && s1 < s2 + c2 { 24 | return -1 25 | } 26 | 27 | if c2 == 0 && s2 < s1 + c1 { 28 | return -1 29 | } 30 | 31 | return max(s1 + c1, s2 + c2) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /2501-3000/2919. Minimum Increment Operations to Make Array Beautiful.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2919. Minimum Increment Operations to Make Array Beautiful 5 | 6 | // Time Complexity: O(n) 7 | // Space Complexity: O(1) 8 | 9 | func minIncrementOperations(_ nums: [Int], _ k: Int) -> Int { 10 | var dp1 = 0 11 | var dp2 = 0 12 | var dp3 = 0 13 | 14 | for a in nums { 15 | let temp1 = dp1 16 | let temp2 = dp2 17 | dp1 = temp2 18 | dp2 = dp3 19 | dp3 = min(temp1, temp2, dp3) + max(k - a, 0) 20 | } 21 | 22 | return min(dp1, dp2, dp3) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /2501-3000/2923. Find Champion I.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2923. Find Champion I 5 | 6 | func findChampion(_ grid: [[Int]]) -> Int { 7 | for i in 0.. Int { 7 | var ans = -1 8 | var count = 0 9 | var indegree = Array(repeating: 0, count: n) 10 | 11 | for e in edges { 12 | indegree[e[1]] += 1 13 | } 14 | 15 | for i in 0.. 1 ? -1 : ans 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /2501-3000/2928. Distribute Candies Among Children I.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2928. Distribute Candies Among Children I 5 | 6 | func distributeCandies(_ n: Int, _ limit: Int) -> Int { 7 | var count = 0 8 | 9 | for i in 0...(min(n, limit)) { 10 | for j in 0...(min(n - i, limit)) { 11 | let k = n - i - j 12 | if k >= 0 && k <= limit { 13 | count += 1 14 | } 15 | } 16 | } 17 | 18 | return count 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2929. Distribute Candies Among Children II.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2929. Distribute Candies Among Children II 5 | 6 | func distributeCandies(_ n: Int, _ limit: Int) -> Int { 7 | return Int( 8 | c(n + 2, 2) - 3 * c(n - limit + 1, 2) + 3 * c(n - 2 * limit, 2) 9 | - c(n - 3 * limit - 1, 2)) 10 | } 11 | 12 | func c(_ n: Int, _ m: Int) -> Int { 13 | guard n >= m else { return 0 } 14 | return n * (n - 1) / (m * (m - 1)) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /2501-3000/2930. Number of Strings Which Can Be Rearranged to Contain Substring.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2930. Number of Strings Which Can Be Rearranged to Contain Substring 5 | 6 | // Time complexity: O(log⁡n) 7 | // Space complexity: O(1) 8 | 9 | private func pow(_ x: Int, _ n: Int, _ mod: Int) -> Int { 10 | var result = 1 11 | var p = x % mod 12 | 13 | var n = n 14 | while n > 0 { 15 | if n & 1 == 1 { 16 | result = (result * p) % mod 17 | } 18 | p = (p * p) % mod 19 | n >>= 1 20 | } 21 | 22 | return result 23 | } 24 | 25 | func stringCount(_ n: Int) -> Int { 26 | let mod = 1_000_000_007 27 | return 28 | ((pow(26, n, mod) 29 | - (n + 75) * pow(25, n - 1, mod) 30 | + (2 * n + 72) * pow(24, n - 1, mod) 31 | - (n + 23) * pow(23, n - 1, mod)) % mod + mod) % mod 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /2501-3000/2931. Maximum Spending After Buying Items.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2931. Maximum Spending After Buying Items 5 | 6 | // Time complexity: O(n logn) 7 | // Space complexity: O(n) 8 | 9 | func maxSpending(_ values: [[Int]]) -> Int { 10 | // Alias for long long data type 11 | typealias ll = Int64 12 | 13 | // Flatten the 2D array into a 1D array 14 | var flattenedValues: [ll] = [] 15 | for row in values { 16 | flattenedValues.append(contentsOf: row.map { ll($0) }) 17 | } 18 | 19 | // Sort the values in ascending order 20 | flattenedValues.sort() 21 | 22 | // Variable to store the final result 23 | var ans: ll = 0 24 | 25 | // Calculate the maximum spending 26 | for i in 0.. Int { 10 | var ans = 0 11 | 12 | // Iterate through each pair of numbers in the array. 13 | for x in nums { 14 | for y in nums { 15 | // Check if the pair (x, y) is a strong pair. 16 | if abs(x - y) <= min(x, y) { 17 | // Update the maximum XOR value. 18 | ans = max(ans, x ^ y) 19 | } 20 | } 21 | } 22 | 23 | // Return the maximum XOR value of strong pairs. 24 | return ans 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /2501-3000/2937. Make Three Strings Equal.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2937. Make Three Strings Equal 5 | 6 | func findMinimumOperations(_ s1: String, _ s2: String, _ s3: String) -> Int { 7 | var i = 0 8 | let sz = min(s1.count, s2.count, s3.count) 9 | 10 | while i < sz 11 | && s1[s1.index(s1.startIndex, offsetBy: i)] == s2[s2.index(s2.startIndex, offsetBy: i)] 12 | && s2[s2.index(s2.startIndex, offsetBy: i)] == s3[s3.index(s3.startIndex, offsetBy: i)] 13 | { 14 | i += 1 15 | } 16 | 17 | return i == 0 ? -1 : s1.count + s2.count + s3.count - i * 3 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /2501-3000/2938. Separate Black and White Balls.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2938. Separate Black and White Balls 5 | // Two Pointers 6 | 7 | func minimumSteps(_ s: String) -> Int { 8 | var res = 0 9 | var j = 0 10 | 11 | for (i, char) in s.enumerated() { 12 | if char == "0" { 13 | res += i - j 14 | j += 1 15 | } 16 | } 17 | 18 | return res 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2939. Maximum Xor Product.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2939. Maximum Xor Product 5 | 6 | // Time complexity: O(N) 7 | // Space complexity: O(1) 8 | 9 | func maximumXorProduct(_ a: Int, _ b: Int, _ n: Int) -> Int { 10 | let mod = 1_000_000_007 11 | var a = a 12 | var b = b 13 | 14 | for i in (0.. b { 20 | a ^= mask 21 | b |= mask 22 | } 23 | continue 24 | } else if (b & mask) != 0 { 25 | if a < b { 26 | a |= mask 27 | b ^= mask 28 | } 29 | } else { 30 | a |= mask 31 | b |= mask 32 | } 33 | } 34 | 35 | a %= mod 36 | b %= mod 37 | 38 | return (a * b) % mod 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /2501-3000/2942. Find Words Containing Character.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2942. Find Words Containing Character 5 | 6 | // Time complexity: (N * max(length of words)) 7 | // Space complexity: O(N) 8 | 9 | func findWordsContaining(_ words: [String], _ x: Character) -> [Int] { 10 | var result: [Int] = [] 11 | 12 | for (index, word) in words.enumerated() { 13 | if word.contains(x) { 14 | result.append(index) 15 | } 16 | } 17 | 18 | return result 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /2501-3000/2943. Maximize Area of Square Hole in Grid.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2943. Maximize Area of Square Hole in Grid 5 | 6 | func getMaxGap(_ bars: [Int]) -> Int { 7 | var sortedBars = bars.sorted() 8 | var count = 2 9 | var res = 2 10 | 11 | for i in 1.. Int { 24 | let gap = min(getMaxGap(hBars), getMaxGap(vBars)) 25 | return gap * gap 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2944. Minimum Number of Coins for Fruits.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2944. Minimum Number of Coins for Fruits 5 | 6 | // Time Complexity: O(n) 7 | // Space Complexity: O(n) 8 | 9 | func minimumCoins(_ prices: [Int]) -> Int { 10 | let n = prices.count 11 | var dp = [Int](repeating: 0, count: n + 1) 12 | var q = [Int]() // Using an array as a deque 13 | 14 | for i in 0..= dp[i] + prices[i] { 20 | q.removeLast() 21 | } 22 | 23 | q.append(i) 24 | dp[i + 1] = dp[q.first!] + prices[q.first!] 25 | } 26 | 27 | return dp[n] 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2946. Matrix Similarity After Cyclic Shifts.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2946. Matrix Similarity After Cyclic Shifts 5 | 6 | // Time complexity: O (m * n) 7 | // Space complexity: O(1) 8 | 9 | func areSimilar(_ mat: [[Int]], _ k: Int) -> Bool { 10 | for row in mat { 11 | let n = row.count 12 | for i in 0.. Int { 10 | let n = s.count 11 | var v = 0 12 | var l = 1 13 | while l * l % (k * 4) != 0 { 14 | l += 1 15 | } 16 | 17 | let vowels: Set = ["a", "e", "i", "o", "u"] 18 | var seen = Array(repeating: [Int: Int](), count: l) 19 | seen[l - 1][0] = 1 20 | var res: Int64 = 0 21 | 22 | for (i, char) in s.enumerated() { 23 | v += vowels.contains(char) ? 1 : -1 24 | res += Int64(seen[i % l][v] ?? 0) 25 | seen[i % l][v, default: 0] += 1 26 | } 27 | 28 | return Int(res) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /2501-3000/2951. Find the Peaks.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2951. Find the Peaks 5 | 6 | // Time complexity: O(n) 7 | // Space complexity: O(1) 8 | 9 | func findPeaks(_ mountain: [Int]) -> [Int] { 10 | let n = mountain.count 11 | var peaks = [Int]() 12 | 13 | for i in 1..<(n - 1) { 14 | if mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1] { 15 | peaks.append(i) 16 | } 17 | } 18 | 19 | return peaks 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /2501-3000/2952. Minimum Number of Coins to be Added.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2952. Minimum Number of Coins to be Added 5 | 6 | // Time complexity : O(N log N) 7 | // Space complexity: O(1) 8 | 9 | func minimumAddedCoins(_ coins: [Int], _ target: Int) -> Int { 10 | var coins = coins.sorted() 11 | var currentMax = 0 12 | var additions = 0 13 | var index = 0 14 | 15 | while currentMax < target { 16 | if index < coins.count && coins[index] <= currentMax + 1 { 17 | currentMax += coins[index] 18 | index += 1 19 | } else { 20 | currentMax += currentMax + 1 21 | additions += 1 22 | } 23 | } 24 | 25 | return additions 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /2501-3000/2956. Find Common Elements Between Two Arrays.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2956. Find Common Elements Between Two Arrays 5 | 6 | // Time complexity: O(n+m) 7 | // Space complexity: O(n+m) 8 | 9 | func findIntersectionValues(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 10 | let set1 = Set(nums1) 11 | let set2 = Set(nums2) 12 | 13 | var count1 = 0 14 | for num in nums1 { 15 | if set2.contains(num) { 16 | count1 += 1 17 | } 18 | } 19 | 20 | var count2 = 0 21 | for num in nums2 { 22 | if set1.contains(num) { 23 | count2 += 1 24 | } 25 | } 26 | 27 | return [count1, count2] 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2957. Remove Adjacent Almost-Equal Characters.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2957. Remove Adjacent Almost-Equal Characters 5 | 6 | // Time Complexity: O(n) 7 | // Space Complexity: O(1) 8 | 9 | func removeAlmostEqualCharacters(_ word: String) -> Int { 10 | let n = word.count 11 | var k = 0 12 | 13 | var i = 1 14 | while i < n { 15 | let current = word.index(word.startIndex, offsetBy: i) 16 | let previous = word.index(word.startIndex, offsetBy: i - 1) 17 | 18 | if abs(Int(word[current].asciiValue!) - Int(word[previous].asciiValue!)) <= 1 { 19 | 20 | k += 1 21 | i += 2 22 | } else { 23 | i += 1 24 | } 25 | } 26 | 27 | return k 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /2501-3000/2958. Length of Longest Subarray With at Most K Frequency.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2958. Length of Longest Subarray With at Most K Frequency 5 | 6 | // Sliding window 7 | // Time complexity: O(N) 8 | // Space complexity: O(N) 9 | 10 | func maxSubarrayLength(_ nums: [Int], _ k: Int) -> Int { 11 | var freq = [Int: Int]() 12 | var ans = 0 13 | var i = 0 14 | 15 | for j in 0.. k { 19 | freq[nums[i], default: 0] -= 1 20 | i += 1 21 | } 22 | 23 | ans = max(ans, j - i + 1) 24 | } 25 | 26 | return ans 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2501-3000/2960. Count Tested Devices After Test Operations.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2960. Count Tested Devices After Test Operations 5 | 6 | // Time Complexity: O(n) 7 | // Space Complexity: O(1) 8 | 9 | func countTestedDevices(_ batteryPercentages: [Int]) -> Int { 10 | var testedDevices = 0 11 | for percentage in batteryPercentages { 12 | testedDevices += (percentage > testedDevices) ? 1 : 0 13 | } 14 | return testedDevices 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /2501-3000/2961. Double Modular Exponentiation.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2961. Double Modular Exponentiation 5 | 6 | func getGoodIndices(_ variables: [[Int]], _ target: Int) -> [Int] { 7 | var result: [Int] = [] 8 | 9 | func power(_ b: Int, _ p: Int, _ m: Int) -> Int { 10 | if p <= 0 { 11 | return 1 12 | } 13 | var t = power(b, p / 2, m) 14 | t = ((t * t) % m) 15 | return (p % 2 == 1) ? (t * b) % m : t 16 | } 17 | 18 | for i in 0.. Int { 11 | let maxElement = nums.max()! 12 | let n = nums.count 13 | var cur = 0 14 | var i = 0 15 | var res: Int64 = 0 16 | 17 | for j in 0..= k { 20 | cur -= (nums[i] == maxElement) ? 1 : 0 21 | i += 1 22 | } 23 | res += Int64(i) 24 | } 25 | 26 | return Int(res) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /2501-3000/2963. Count the Number of Good Partitions.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2963. Count the Number of Good Partitions 5 | 6 | // Time complexity: O(N) 7 | // Space complexity: O(N) 8 | 9 | func numberOfGoodPartitions(_ nums: [Int]) -> Int { 10 | let m = 1_000_000_007 11 | var count = 0 12 | var last: [Int: Int] = [:] 13 | 14 | for i in 0.. next { 22 | count += 1 23 | } 24 | next = max(next, last[nums[i]]!) 25 | } 26 | 27 | return power(2, count - 1, m) 28 | } 29 | 30 | func power(_ b: Int, _ p: Int, _ m: Int) -> Int { 31 | if p <= 0 { 32 | return 1 33 | } 34 | let t = power(b, p / 2, m) 35 | return (p % 2 == 1) ? (((t * t) % m) * b) % m : (t * t) % m 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /2501-3000/2965. Find Missing and Repeated Values.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2965. Find Missing and Repeated Values 5 | 6 | // Math 7 | // Time complexity: O(n * n) 8 | // Space complexity: O(1) 9 | 10 | func findMissingAndRepeatedValues(_ grid: [[Int]]) -> [Int] { 11 | let n = grid.count 12 | let N = n * n 13 | var sum = 0 14 | var sqrSum = 0 15 | 16 | for i in 0.. [[Int]] { 10 | var ans: [[Int]] = [] 11 | let sortedNums = nums.sorted() 12 | 13 | for i in stride(from: 2, to: sortedNums.count, by: 3) { 14 | if sortedNums[i] - sortedNums[i - 2] > k { 15 | return [] 16 | } 17 | ans.append([sortedNums[i - 2], sortedNums[i - 1], sortedNums[i]]) 18 | } 19 | 20 | return ans 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /2501-3000/2970. Count the Number of Incremovable Subarrays I.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2970. Count the Number of Incremovable Subarrays I 5 | 6 | func incremovableSubarrayCount(_ nums: [Int]) -> Int { 7 | var ans = 0 8 | 9 | for i in 0..= i && k <= j { 16 | continue 17 | } 18 | 19 | if last >= nums[k] { 20 | flag = false 21 | break 22 | } 23 | 24 | last = nums[k] 25 | } 26 | 27 | if flag { 28 | ans += 1 29 | } 30 | } 31 | } 32 | 33 | return ans 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /2501-3000/2971. Find Polygon With the Largest Perimeter.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2971. Find Polygon With the Largest Perimeter 5 | 6 | // Time complexity: O(n) 7 | // Space complexity: O(1) 8 | 9 | func largestPerimeter(_ nums: [Int]) -> Int { 10 | var sortedNums = nums.sorted(by: <) 11 | var sum = 0 12 | 13 | for num in sortedNums { 14 | sum += num 15 | } 16 | 17 | for i in stride(from: sortedNums.count - 1, through: 2, by: -1) { 18 | sum -= sortedNums[i] 19 | if sortedNums[i] < sum { 20 | return sum + sortedNums[i] 21 | } 22 | } 23 | 24 | return -1 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /2501-3000/2974. Minimum Number Game.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2974. Minimum Number Game 5 | 6 | func numberGame(_ nums: [Int]) -> [Int] { 7 | var sortedNums = nums.sorted() 8 | var arr = [Int]() 9 | 10 | for i in stride(from: 1, to: sortedNums.count, by: 2) { 11 | sortedNums.swapAt(i, i - 1) 12 | } 13 | 14 | arr.append(contentsOf: sortedNums) 15 | return arr 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /2501-3000/2980. Check if Bitwise OR Has Trailing Zeros.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2980. Check if Bitwise OR Has Trailing Zeros 5 | 6 | func hasTrailingZeros(_ nums: [Int]) -> Bool { 7 | var evenCount = 0 8 | 9 | for n in nums { 10 | evenCount += (n % 2 == 0) ? 1 : 0 11 | } 12 | 13 | return evenCount >= 2 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /2501-3000/2996. Smallest Missing Integer Greater Than Sequential Prefix Sum.swift: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | // Solution by Sergey Leschev 4 | // 2996. Smallest Missing Integer Greater Than Sequential Prefix Sum 5 | 6 | // Time complexity: O(N * log(N)) 7 | // Space complexity: O(1) 8 | 9 | func missingInteger(_ nums: [Int]) -> Int { 10 | var countSum = nums[0] 11 | var sortedNums = Array(nums) 12 | sortedNums.sort() 13 | 14 | for i in 1..drawing 4 | 5 | drawing 6 | 7 | **Languages**: Swift, Shell, Database (T-SQL, PL/SQL, MySQL), Concurrency (Python3). 8 | 9 | **Algorithms**: linked lists, binary search, hash table, queue/stack, dfs/bfs, sort, heap/hash, two pointers, sliding window, tree, greedy problems etc. 10 | 11 | Other TypeScript solutions: https://github.com/sergeyleschev/leetcode-typescript 12 | --------------------------------------------------------------------------------