├── 1. Two Sum.c ├── 10. Regular Expression Matching.c ├── 1007. Minimum Domino Rotations For Equal Row.c ├── 1008. Construct Binary Search Tree from Preorder Traversal.c ├── 101. Symmetric Tree.c ├── 1011. Capacity To Ship Packages Within D Days.c ├── 102. Binary Tree Level Order Traversal.c ├── 103. Binary Tree Zigzag Level Order Traversal.c ├── 104. Maximum Depth of Binary Tree.c ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.c ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.c ├── 107. Binary Tree Level Order Traversal II.c ├── 108. Convert Sorted Array to Binary Search Tree.c ├── 11. Container With Most Water.c ├── 114. Flatten Binary Tree to Linked List.c ├── 116. Populating Next Right Pointers in Each Node.c ├── 117. Populating Next Right Pointers in Each Node II.c ├── 118. Pascal's Triangle.c ├── 12. Integer to Roman.c ├── 120. Triangle.c ├── 121. Best Time to Buy and Sell Stock.c ├── 122. Best Time to Buy and Sell Stock II.c ├── 123. Best Time to Buy and Sell Stock III.c ├── 124. Binary Tree Maximum Path Sum.c ├── 125. Valid Palindrome.c ├── 126. Word Ladder II.c ├── 127. Word Ladder.c ├── 128. Longest Consecutive Sequence.c ├── 13. Roman to Integer.c ├── 131. Palindrome Partitioning.c ├── 132. Palindrome Partitioning II.c ├── 133. Clone Graph.c ├── 135. Candy.c ├── 136. Single Number.c ├── 137. Single Number II.c ├── 138. Copy List with Random Pointer.c ├── 139. Word Break.c ├── 14. Longest Common Prefix.c ├── 140. Word Break II.c ├── 141. Linked List Cycle.c ├── 142. Linked List Cycle II.c ├── 144. Binary Tree Preorder Traversal.c ├── 145. Binary Tree Postorder Traversal.c ├── 146. LRU Cache.c ├── 148. Sort List.c ├── 149. Max Points on a Line.c ├── 15. 3Sum.c ├── 151. Reverse Words in a String.c ├── 152. Maximum Product Subarray.c ├── 155. Min Stack.c ├── 156. Binary Tree Upside Down.c ├── 158. Read N Characters Given Read4 II - Call multiple times.c ├── 159. Longest Substring with At Most Two Distinct Characters.c ├── 16. 3Sum Closest.c ├── 160. Intersection of Two Linked Lists.c ├── 161. One Edit Distance.c ├── 162. Find Peak Element.c ├── 163. Missing Ranges.c ├── 165. Compare Version Numbers.c ├── 166. Fraction to Recurring Decimal.c ├── 167. Two Sum II - Input array is sorted.c ├── 168. Excel Sheet Column Title.c ├── 17. Letter Combinations of a Phone Number.c ├── 170. Two Sum III - Data structure design.c ├── 171. Excel Sheet Column Number.c ├── 173. Binary Search Tree Iterator.c ├── 186. Reverse Words in a String II.c ├── 187. Repeated DNA Sequences.c ├── 188. Best Time to Buy and Sell Stock IV.c ├── 19. Remove Nth Node From End of List.c ├── 190. Reverse Bits.c ├── 191. Number of 1 Bits.c ├── 198. House Robber.c ├── 199. Binary Tree Right Side View.c ├── 2. Add Two Numbers.c ├── 20. Valid Parentheses.c ├── 200. Number of Islands.c ├── 202. Happy Number.c ├── 205. Isomorphic Strings.c ├── 206. Reverse Linked List.c ├── 207. Course Schedule.c ├── 208. Implement Trie (Prefix Tree).c ├── 209. Minimum Size Subarray Sum.c ├── 21. Merge Two Sorted Lists.c ├── 210. Course Schedule II.c ├── 211. Add and Search Word - Data structure design.c ├── 212. Word Search II.c ├── 213. House Robber II.c ├── 214. Shortest Palindrome.c ├── 215. Kth Largest Element in an Array.c ├── 217. Contains Duplicate.c ├── 218. The Skyline Problem.c ├── 219. Contains Duplicate II.c ├── 22. Generate Parentheses.c ├── 220. Contains Duplicate III.c ├── 221. Maximal Square.c ├── 222. Count Complete Tree Nodes.c ├── 223. Rectangle Area.c ├── 224. Basic Calculator.c ├── 227. Basic Calculator II.c ├── 228. Summary Ranges.c ├── 229. Majority Element II.c ├── 23. Merge k Sorted Lists.c ├── 230. Kth Smallest Element in a BST.c ├── 231. Power of Two.c ├── 234. Palindrome Linked List.c ├── 235. Lowest Common Ancestor of a Binary Search Tree.c ├── 236. Lowest Common Ancestor of a Binary Tree.c ├── 237. Delete Node in a Linked List.c ├── 238. Product of Array Except Self.c ├── 239. Sliding Window Maximum.c ├── 24. Swap Nodes in Pairs.c ├── 240. Search a 2D Matrix II.c ├── 241. Different Ways to Add Parentheses.c ├── 242. Valid Anagram.c ├── 243. Shortest Word Distance.c ├── 244. Shortest Word Distance II.c ├── 245. Shortest Word Distance III.c ├── 246. Strobogrammatic Number.c ├── 247. Strobogrammatic Number II.c ├── 249. Group Shifted Strings.c ├── 25. Reverse Nodes in k-Group.c ├── 251. Flatten 2D Vector.c ├── 253. Meeting Rooms II.c ├── 254. Factor Combinations.c ├── 256. Paint House.c ├── 257. Binary Tree Paths.c ├── 259. 3Sum Smaller.c ├── 26. Remove Duplicates from Sorted Array.c ├── 260. Single Number III.c ├── 261. Graph Valid Tree.c ├── 263. Ugly Number.c ├── 264. Ugly Number II.c ├── 265. Paint House II.c ├── 266. Palindrome Permutation.c ├── 268. Missing Number.c ├── 269. Alien Dictionary.c ├── 27. Remove Element.c ├── 270. Closest Binary Search Tree Value.c ├── 271. Encode and Decode Strings.c ├── 272. Closest Binary Search Tree Value II.c ├── 273. Integer to English Words.c ├── 274. H-Index.c ├── 275. H-Index II.c ├── 276. Paint Fence.c ├── 277. Find the Celebrity.c ├── 278. First Bad Version.c ├── 279. Perfect Squares.c ├── 28. Implement strStr().c ├── 280. Wiggle Sort.c ├── 281. Zigzag Iterator.c ├── 282. Expression Add Operators.c ├── 283. Move Zeroes.c ├── 285. Inorder Successor in BST.c ├── 286. Walls and Gates.c ├── 287. Find the Duplicate Number.c ├── 288. Unique Word Abbreviation.c ├── 289. Game of Life.c ├── 290. Word Pattern.c ├── 291. Word Pattern II.c ├── 292. Nim Game.c ├── 293. Flip Game.c ├── 294. Flip Game II.c ├── 295. Find Median from Data Stream.c ├── 297. Serialize and Deserialize Binary Tree.c ├── 298. Binary Tree Longest Consecutive Sequence.c ├── 3. Longest Substring Without Repeating Characters.c ├── 30. Substring with Concatenation of All Words.c ├── 300. Longest Increasing Subsequence.c ├── 301. Remove Invalid Parentheses.c ├── 302. Smallest Rectangle Enclosing Black Pixels.c ├── 305. Number of Islands II.c ├── 308. Range Sum Query 2D - Mutable.c ├── 309. Best Time to Buy and Sell Stock with Cooldown.c ├── 31. Next Permutation.c ├── 311. Sparse Matrix Multiplication.c ├── 314. Binary Tree Vertical Order Traversal.c ├── 315. Count of Smaller Numbers After Self.c ├── 317. Shortest Distance from All Buildings.c ├── 318. Maximum Product of Word Lengths.c ├── 32. Longest Valid Parentheses.c ├── 320. Generalized Abbreviation.c ├── 322. Coin Change.c ├── 323. Number of Connected Components in an Undirected Graph.c ├── 324. Wiggle Sort II.c ├── 325. Maximum Size Subarray Sum Equals k.c ├── 326. Power of Three.c ├── 327. Count of Range Sum.c ├── 329. Longest Increasing Path in a Matrix.c ├── 33. Search in Rotated Sorted Array.c ├── 332. Reconstruct Itinerary.c ├── 333. Largest BST Subtree.c ├── 334. Increasing Triplet Subsequence.c ├── 336. Palindrome Pairs.c ├── 337. House Robber III.c ├── 338. Counting Bits.c ├── 339. Nested List Weight Sum.c ├── 34. Search for a Range.c ├── 340. Longest Substring with At Most K Distinct Characters.c ├── 341. Flatten Nested List Iterator.c ├── 342. Power of Four.c ├── 344. Reverse String.c ├── 345. Reverse Vowels of a String.c ├── 346. Moving Average from Data Stream.c ├── 348. Design Tic-Tac-Toe.c ├── 350. Intersection of Two Arrays II.c ├── 351. Android Unlock Patterns.c ├── 358. Rearrange String k Distance Apart.c ├── 359. Logger Rate Limiter.c ├── 36. Valid Sudoku.c ├── 360. Sort Transformed Array.c ├── 361. Bomb Enemy.c ├── 362. Design Hit Counter.c ├── 363. Max Sum of Rectangle No Larger Than K.c ├── 364. Nested List Weight Sum II.c ├── 366. Find Leaves of Binary Tree.c ├── 367. Valid Perfect Square.c ├── 369. Plus One Linked List.c ├── 37. Sudoku Solver.c ├── 373. Find K Pairs with Smallest Sums.c ├── 375. Guess Number Higher or Lower II.c ├── 377. Combination Sum IV.c ├── 378. Kth Smallest Element in a Sorted Matrix.c ├── 379. Design Phone Directory.c ├── 38. Count and Say.c ├── 380. Insert Delete GetRandom O(1).c ├── 382. Linked List Random Node.c ├── 383. Ransom Note.c ├── 387. First Unique Character in a String.c ├── 388. Longest Absolute File Path.c ├── 389. Find the Difference.c ├── 39. Combination Sum.c ├── 391. Perfect Rectangle.c ├── 392. Is Subsequence.c ├── 393. UTF-8 Validation.c ├── 394. Decode String.c ├── 397. Integer Replacement.c ├── 398. Random Pick Index.c ├── 399. Evaluate Division.c ├── 4. Median of Two Sorted Arrays.c ├── 40. Combination Sum II.c ├── 400. Nth Digit.c ├── 401. Binary Watch.c ├── 402. Remove K Digits.c ├── 403. Frog Jump.c ├── 404. Sum of Left Leaves.c ├── 406. Queue Reconstruction by Height.c ├── 407. Trapping Rain Water II.c ├── 408. Valid Word Abbreviation.c ├── 409. Longest Palindrome.c ├── 41. First Missing Positive.c ├── 410. Split Array Largest Sum.c ├── 411. Minimum Unique Word Abbreviation.c ├── 415. Add Strings.c ├── 416. Partition Equal Subset Sum.c ├── 417. Pacific Atlantic Water Flow.c ├── 418. Sentence Screen Fitting.c ├── 42. Trapping Rain Water.c ├── 421. Maximum XOR of Two Numbers in an Array.c ├── 422. Valid Word Square.c ├── 424. Longest Repeating Character Replacement.c ├── 425. Word Squares.c ├── 426. Convert Binary Search Tree to Sorted Doubly Linked List.py ├── 43. Multiply Strings.c ├── 437. Path Sum III.c ├── 438. Find All Anagrams in a String.c ├── 44. Wildcard Matching.c ├── 444. Sequence Reconstruction.c ├── 447. Number of Boomerangs.c ├── 448. Find All Numbers Disappeared in an Array.c ├── 450. Delete Node in a BST.c ├── 459. Repeated Substring Pattern.c ├── 46. Permutations.c ├── 460. LFU Cache.c ├── 461. Hamming Distance.c ├── 463. Island Perimeter.c ├── 464. Can I Win.c ├── 465. Optimal Account Balancing.c ├── 47. Permutations II.c ├── 471. Encode String with Shortest Length.c ├── 475. Heaters.c ├── 476. Number Complement.c ├── 477. Total Hamming Distance.c ├── 48. Rotate Image.c ├── 482. License Key Formatting.c ├── 484. Find Permutation.c ├── 486. Predict the Winner.c ├── 489. Robot Room Cleaner.py ├── 49. Group Anagrams.c ├── 490. The Maze.c ├── 494. Target Sum.c ├── 5. Longest Palindromic Substring.c ├── 50. Pow(x, n).c ├── 51. N-Queens.c ├── 516. Longest Palindromic Subsequence.c ├── 52. N-Queens II.c ├── 523. Continuous Subarray Sum.c ├── 525. Contiguous Array.c ├── 527. Word Abbreviation.c ├── 53. Maximum Subarray.c ├── 54. Spiral Matrix.c ├── 543. Diameter of Binary Tree.c ├── 545. Boundary of Binary Tree.c ├── 548. Split Array with Equal Sum.c ├── 554. Brick Wall.c ├── 56. Merge Intervals.c ├── 560. Subarray Sum Equals K.c ├── 567. Permutation in String.c ├── 57. Insert Interval.c ├── 572. Subtree of Another Tree.c ├── 587. Erect the Fence.c ├── 59. Spiral Matrix II.c ├── 6. ZigZag Conversion.c ├── 62. Unique Paths.c ├── 621. Task Scheduler.c ├── 630. Course Schedule III.c ├── 636. Exclusive Time of Functions.c ├── 639. Decode Ways II.c ├── 646. Maximum Length of Pair Chain.c ├── 647. Palindromic Substrings.c ├── 648. Replace Words.c ├── 65. Valid Number.c ├── 66. Plus One.c ├── 673. Number of Longest Increasing Subsequence.c ├── 68. Text Justification.c ├── 687. Longest Univalue Path.c ├── 689. Maximum Sum of 3 Non-Overlapping Subarrays.c ├── 69. Sqrt(x).c ├── 693. Binary Number with Alternating Bits.c ├── 7. Reverse Integer.c ├── 70. Climbing Stairs.c ├── 71. Simplify Path.c ├── 714. Best Time to Buy and Sell Stock with Transaction Fee.c ├── 72. Edit Distance.c ├── 723. Candy Crush.c ├── 736. Parse Lisp Expression.c ├── 74. Search a 2D Matrix.c ├── 75. Sort Colors.c ├── 751. IP to CIDR.c ├── 76. Minimum Window Substring.c ├── 762. Prime Number of Set Bits in Binary Representation.c ├── 767. Reorganize String.c ├── 77. Combinations.c ├── 774. Minimize Max Distance to Gas Station.c ├── 777. Swap Adjacent in LR String.c ├── 78. Subsets.c ├── 780. Reaching Points.c ├── 79. Word Search.c ├── 8. String to Integer (atoi).c ├── 80. Remove Duplicates from Sorted Array II.c ├── 809. Expressive Words.c ├── 81. Search in Rotated Sorted Array II.c ├── 82. Remove Duplicates from Sorted List II.c ├── 83. Remove Duplicates from Sorted List.c ├── 833. Find And Replace in String.c ├── 843. Guess the Word.c ├── 85. Maximal Rectangle.c ├── 857. Minimum Cost to Hire K Workers.c ├── 863. All Nodes Distance K in Binary Tree.c ├── 865. Smallest Subtree with all the Deepest Nodes.c ├── 88. Merge Sorted Array.c ├── 89. Gray Code.c ├── 9. Palindrome Number.c ├── 90. Subsets II.c ├── 904. Fruit Into Baskets.c ├── 91. Decode Ways.c ├── 911. Online Election.c ├── 913. Cat and Mouse.c ├── 920. Number of Music Playlists.c ├── 926. Flip String to Monotone Increasing.c ├── 93. Restore IP Addresses.c ├── 935. Knight Dialer.c ├── 939. Minimum Area Rectangle.c ├── 94. Binary Tree Inorder Traversal.c ├── 943. Find the Shortest Superstring.c ├── 947. Most Stones Removed with Same Row or Column.c ├── 958. Check Completeness of a Binary Tree.c ├── 96. Unique Binary Search Trees.c ├── 973. K Closest Points to Origin.c ├── 975. Odd Even Jump.c ├── 98. Validate Binary Search Tree.c ├── 986. Interval List Intersections.c ├── 987. Vertical Order Traversal of a Binary Tree.c ├── 99. Recover Binary Search Tree.c ├── 992. Subarrays with K Different Integers.c ├── README.md ├── alternate_threads.c ├── elevator.c ├── pipe.c └── tool.js /1008. Construct Binary Search Tree from Preorder Traversal.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1008. Construct Binary Search Tree from Preorder Traversal 3 | 4 | Return the root node of a binary search tree that matches the given preorder traversal. 5 | 6 | (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val.  Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) 7 | 8 |   9 | 10 | Example 1: 11 | 12 | Input: [8,5,1,7,10,12] 13 | Output: [8,5,10,1,7,null,12] 14 | 15 | 16 | 17 |   18 | 19 | Note:  20 | 21 | 22 | 1 <= preorder.length <= 100 23 | The values of preorder are distinct. 24 | */ 25 | 26 | /** 27 | * Definition for a binary tree node. 28 | * struct TreeNode { 29 | *     int val; 30 | *     struct TreeNode *left; 31 | *     struct TreeNode *right; 32 | * }; 33 | */ 34 | struct TreeNode* bstFromPreorder(int* preorder, int preorderSize) { 35 |    struct TreeNode *node; 36 |    int mid; 37 |     38 |    if (preorderSize == 0) return NULL; 39 |     40 |    node = malloc(sizeof(struct TreeNode)); 41 |    //assert(node); 42 |    node->val = preorder[0]; 43 |     44 |    mid = 1; 45 |    while (mid < preorderSize && preorder[mid] < node->val) { 46 |        mid ++; 47 |   } 48 |    node->left = bstFromPreorder(&preorder[1], mid - 1); 49 |    node->right = bstFromPreorder(&preorder[mid], preorderSize - mid); 50 | 51 |    return node; 52 | } 53 | 54 | 55 | /* 56 | Difficulty:Medium 57 | 58 | 59 | */ 60 | -------------------------------------------------------------------------------- /104. Maximum Depth of Binary Tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | 104. Maximum Depth of Binary Tree 3 | 4 | Given a binary tree, find its maximum depth. 5 | 6 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 7 | */ 8 | 9 | /** 10 | * Definition for a binary tree node. 11 | * struct TreeNode { 12 | *     int val; 13 | *     struct TreeNode *left; 14 | *     struct TreeNode *right; 15 | * }; 16 | */ 17 | int maxDepth(struct TreeNode* root) { 18 |    int l, r; 19 |     20 |    if (!root) return 0; 21 |     22 |    l = maxDepth(root->left) + 1; 23 |    r = maxDepth(root->right) + 1; 24 |     25 |    return l > r ? l : r; 26 | } 27 | 28 | 29 | /* 30 | Difficulty:Easy 31 | Total Accepted:256.9K 32 | Total Submissions:488K 33 | 34 | 35 | Companies LinkedIn Uber Apple Yahoo 36 | Related Topics Tree Depth-first Search 37 | Similar Questions 38 | 39 | 40 | Balanced Binary Tree 41 | 42 | Minimum Depth of Binary Tree 43 | */ 44 | -------------------------------------------------------------------------------- /105. Construct Binary Tree from Preorder and Inorder Traversal.c: -------------------------------------------------------------------------------- 1 | /* 2 | 105. Construct Binary Tree from Preorder and Inorder Traversal 3 | 4 | Given preorder and inorder traversal of a tree, construct the binary tree. 5 | 6 | Note: 7 | You may assume that duplicates do not exist in the tree. 8 | 9 | For example, given 10 | 11 | preorder = [3,9,20,15,7] 12 | inorder = [9,3,15,20,7] 13 | 14 | Return the following binary tree: 15 | 16 | 3 17 | / \ 18 | 9 20 19 | / \ 20 | 15 7 21 | */ 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * struct TreeNode { 26 | *     int val; 27 | *     struct TreeNode *left; 28 | *     struct TreeNode *right; 29 | * }; 30 | */ 31 | typedef struct { 32 |    int *preorder; 33 |    int pre_idx; 34 |    int pre_sz; 35 |    int *inorder; 36 | } data_t; 37 | ​ 38 | struct TreeNode *make_tree(data_t *data, int start, int end) { 39 |    struct TreeNode *node; 40 |    int i; 41 | 42 |    if (start == end) return NULL; 43 |     44 |    node = malloc(sizeof(struct TreeNode)); 45 |    //assert(node); 46 |    node->val = data->preorder[data->pre_idx ++]; 47 |     48 |    i = start; 49 |    while (i < end && data->inorder[i] != node->val) i ++; 50 |     51 |    node->left = make_tree(data, start, i); 52 |    node->right = make_tree(data, i + 1, end); 53 |     54 |    return node; 55 | } 56 | ​ 57 | struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) { 58 |    data_t data; 59 |     60 |    data.preorder = preorder; 61 |    data.pre_idx = 0; 62 |    data.pre_sz = preorderSize; 63 |    data.inorder = inorder; 64 |     65 |    return make_tree(&data, 0, inorderSize); 66 | } 67 | 68 | 69 | /* 70 | Difficulty:Medium 71 | 72 | 73 | */ 74 | -------------------------------------------------------------------------------- /106. Construct Binary Tree from Inorder and Postorder Traversal.c: -------------------------------------------------------------------------------- 1 | /* 2 | 106. Construct Binary Tree from Inorder and Postorder Traversal 3 | 4 | Given inorder and postorder traversal of a tree, construct the binary tree. 5 | 6 | Note: 7 | You may assume that duplicates do not exist in the tree. 8 | 9 | For example, given 10 | 11 | inorder = [9,3,15,20,7] 12 | postorder = [9,15,7,20,3] 13 | 14 | Return the following binary tree: 15 | 16 | 3 17 | / \ 18 | 9 20 19 | / \ 20 | 15 7 21 | */ 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * struct TreeNode { 26 | *     int val; 27 | *     struct TreeNode *left; 28 | *     struct TreeNode *right; 29 | * }; 30 | */ 31 | typedef struct { 32 |    int *postorder; 33 |    int post_idx; 34 |    int *inorder; 35 | } data_t; 36 | 37 | struct TreeNode *make_tree(data_t *data, int start, int end) { 38 |    struct TreeNode *node; 39 |    int i; 40 |     41 |    if (start == end) return NULL; 42 |     43 |    node = malloc(sizeof(struct TreeNode)); 44 |    //assert(node); 45 |    node->val = data->postorder[-- data->post_idx]; 46 |     47 |    i = start; 48 |    while (i < end && data->inorder[i] != node->val) i ++; 49 |     50 |    node->right = make_tree(data, i + 1, end); 51 |    node->left = make_tree(data, start, i); 52 |     53 |    return node; 54 | } 55 | ​ 56 | struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) { 57 |    data_t data; 58 |    data.postorder = postorder; 59 |    data.post_idx = postorderSize; 60 |    data.inorder = inorder; 61 |    return make_tree(&data, 0, inorderSize); 62 | } 63 | 64 | 65 | /* 66 | Difficulty:Medium 67 | 68 | 69 | */ 70 | -------------------------------------------------------------------------------- /108. Convert Sorted Array to Binary Search Tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | 108. Convert Sorted Array to Binary Search Tree 3 | 4 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 5 | */ 6 | 7 | /** 8 | * Definition for a binary tree node. 9 | * struct TreeNode { 10 | *     int val; 11 | *     struct TreeNode *left; 12 | *     struct TreeNode *right; 13 | * }; 14 | */ 15 | struct TreeNode *gen_tree(int *nums, int start, int end) { 16 |    struct TreeNode *node; 17 |    int mid; 18 |     19 |    if (start > end) return NULL; 20 |     21 |    node = malloc(sizeof(struct TreeNode)); 22 |    //assert(node); 23 |     24 |    mid = start + (end - start) / 2; 25 |    node->val = nums[mid]; 26 |    node->left = gen_tree(nums, start, mid - 1);  // sub tree on left 27 |    node->right = gen_tree(nums, mid + 1, end);  // sub tree on right 28 |     29 |    return node; 30 | } 31 | struct TreeNode* sortedArrayToBST(int* nums, int numsSize) { 32 |    return gen_tree(nums, 0, numsSize - 1); 33 | } 34 | 35 | 36 | /* 37 | Difficulty:Easy 38 | Total Accepted:133.7K 39 | Total Submissions:317.4K 40 | 41 | 42 | Companies Airbnb 43 | Related Topics Tree Depth-first Search 44 | Similar Questions 45 | 46 | 47 | Convert Sorted List to Binary Search Tree 48 | */ 49 | -------------------------------------------------------------------------------- /11. Container With Most Water.c: -------------------------------------------------------------------------------- 1 | /* 2 | 11. Container With Most Water 3 | 4 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 5 | 6 | Note: You may not slant the container and n is at least 2. 7 | */ 8 | 9 | int maxArea(int* height, int heightSize) { 10 |    int l, r, x, water, max = 0; 11 |    int i, j; 12 | #if 0 13 |    for (i = 0; i < heightSize - 1; i ++) { 14 |        if (i == 0 || height[i] > l) { 15 |            l = height[i]; 16 |            for (j = i + 1; j < heightSize; j ++) { 17 |                r = height[j]; 18 |                x = l < r ? l : r; 19 |                water = x * (j - i); 20 |                if (max < water) max = water; 21 |           } 22 |       } 23 |   } 24 | #else 25 |    i = 0; 26 |    j = heightSize - 1; 27 |    while (i < j) { 28 |        l = height[i]; 29 |        r = height[j]; 30 |        x = l < r ? l : r; 31 |        water = x * (j - i); 32 |        if (max < water) max = water; 33 |        if (l < r) i ++; 34 |        else j --; 35 |   } 36 | #endif 37 |    return max; 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Medium 43 | Total Accepted:144.5K 44 | Total Submissions:395.2K 45 | 46 | 47 | Companies Bloomberg 48 | Related Topics Array Two Pointers 49 | Similar Questions 50 | 51 | 52 | Trapping Rain Water 53 | */ 54 | -------------------------------------------------------------------------------- /114. Flatten Binary Tree to Linked List.c: -------------------------------------------------------------------------------- 1 | /* 2 | 114. Flatten Binary Tree to Linked List 3 | 4 | Given a binary tree, flatten it to a linked list in-place. 5 | 6 | For example, given the following tree: 7 | 8 | 1 9 | / \ 10 | 2 5 11 | / \ \ 12 | 3 4 6 13 | 14 | 15 | The flattened tree should look like: 16 | 17 | 1 18 | \ 19 | 2 20 | \ 21 | 3 22 | \ 23 | 4 24 | \ 25 | 5 26 | \ 27 | 6 28 | */ 29 | 30 | /** 31 | * Definition for a binary tree node. 32 | * struct TreeNode { 33 | *     int val; 34 | *     struct TreeNode *left; 35 | *     struct TreeNode *right; 36 | * }; 37 | */ 38 | struct TreeNode *preOrderTraversal(struct TreeNode *prev, struct TreeNode *node) { 39 |    struct TreeNode *left, *right; 40 |     41 |    if (!node) return prev; 42 |     43 |    left = node->left; 44 |    right = node->right; 45 |    node->left = node->right = NULL; 46 |     47 |    prev->right = node; 48 |    prev = node; 49 | 50 |    prev = preOrderTraversal(prev, left);   // it's import to update prev 51 |    prev = preOrderTraversal(prev, right); 52 |     53 |    return prev; 54 | } 55 | void flatten(struct TreeNode* root) { 56 |    struct TreeNode head = { 0 }; 57 |    preOrderTraversal(&head, root); 58 | } 59 | 60 | 61 | /* 62 | Difficulty:Medium 63 | 64 | 65 | */ 66 | -------------------------------------------------------------------------------- /118. Pascal's Triangle.c: -------------------------------------------------------------------------------- 1 | /* 2 | 118. Pascal's Triangle 3 | 4 | Given numRows, generate the first numRows of Pascal's triangle. 5 | 6 | 7 | For example, given numRows = 5, 8 | Return 9 | [ 10 | [1], 11 | [1,1], 12 | [1,2,1], 13 | [1,3,3,1], 14 | [1,4,6,4,1] 15 | ] 16 | */ 17 | 18 | /** 19 | * Return an array of arrays. 20 | * The sizes of the arrays are returned as *columnSizes array. 21 | * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). 22 | */ 23 | int** generate(int numRows, int** columnSizes) { 24 |    int i, j; 25 |    int *buff, **p; 26 |    p = malloc(numRows * sizeof(int *)); 27 |    *columnSizes = malloc(numRows * sizeof(int)); 28 |    //assert(p && *columnSizes); 29 |    for (i = 1; i <= numRows; i ++) { 30 |        buff = malloc(i * sizeof(int)); 31 |        //assert(buff); 32 |        p[i - 1] = buff; 33 |       (*columnSizes)[i - 1] = i; 34 |        buff[0] = 1; 35 |        for (j = 1; j < i - 1; j ++) { 36 |            buff[j] = p[i - 2][j - 1] + p[i - 2][j]; 37 |       } 38 |        buff[i - 1] = 1; 39 |   } 40 |    return p; 41 | } 42 | 43 | 44 | /* 45 | Difficulty:Easy 46 | Total Accepted:137.9K 47 | Total Submissions:357.7K 48 | 49 | 50 | Companies Apple Twitter 51 | Related Topics Array 52 | Similar Questions 53 | 54 | 55 | Pascal's Triangle II 56 | */ 57 | -------------------------------------------------------------------------------- /120. Triangle.c: -------------------------------------------------------------------------------- 1 | /* 2 | 120. Triangle 3 | 4 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 5 | 6 | 7 | For example, given the following triangle 8 | [ 9 | [2], 10 | [3,4], 11 | [6,5,7], 12 | [4,1,8,3] 13 | ] 14 | 15 | 16 | 17 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 18 | 19 | 20 | 21 | Note: 22 | Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 23 | */ 24 | 25 | int minimumTotal(int** triangle, int triangleRowSize, int *triangleColSizes) { 26 |    int *x; 27 |    int i, j, k; 28 |     29 |    if (triangleRowSize == 1) return triangle[0][0]; 30 |     31 |    x = malloc(triangleRowSize * sizeof(int)); 32 |    if (!x) return 0; 33 |     34 |    for (i = triangleRowSize - 1; i >= 0 ; i --) { 35 |        for (j = 0; j < triangleColSizes[i]; j ++) { 36 |            if (i == triangleRowSize - 1) { 37 |                k = 0; 38 |           } else if (x[j] < x[j + 1]) { 39 |                k = x[j]; 40 |           } else { 41 |                k = x[j + 1]; 42 |           } 43 |            k += triangle[i][j]; 44 |            x[j] = k; 45 |       } 46 |   } 47 |    free(x); 48 |    return k; 49 | } 50 | 51 | 52 | /* 53 | Difficulty:Medium 54 | Total Accepted:109.4K 55 | Total Submissions:323.7K 56 | 57 | 58 | Related Topics Array Dynamic Programming 59 | 60 | */ 61 | -------------------------------------------------------------------------------- /121. Best Time to Buy and Sell Stock.c: -------------------------------------------------------------------------------- 1 | /* 2 | 121. Best Time to Buy and Sell Stock 3 | 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 7 | 8 | Example 1: 9 | Input: [7, 1, 5, 3, 6, 4] 10 | Output: 5 11 | 12 | max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) 13 | 14 | 15 | 16 | Example 2: 17 | Input: [7, 6, 4, 3, 1] 18 | Output: 0 19 | 20 | In this case, no transaction is done, i.e. max profit = 0. 21 | */ 22 | 23 | int maxProfit(int* prices, int pricesSize) { 24 | int i, d, k = 0; 25 | 26 | if (pricesSize < 2) return 0; 27 | 28 | // O(n) 29 | int cost = prices[0]; 30 | for (i = 1; i < pricesSize; i ++) { 31 | if (prices[i] > cost) { 32 | d = prices[i] - cost; 33 | k = d > k ? d : k; 34 | } else { 35 | cost = prices[i]; 36 | } 37 | } 38 | 39 | return k; 40 | } 41 | 42 | 43 | /* 44 | Difficulty:Easy 45 | Total Accepted:207.9K 46 | Total Submissions:504.8K 47 | 48 | 49 | Companies Amazon Microsoft Bloomberg Uber Facebook 50 | Related Topics Array Dynamic Programming 51 | Similar Questions 52 | 53 | 54 | Maximum Subarray 55 | 56 | Best Time to Buy and Sell Stock II 57 | 58 | Best Time to Buy and Sell Stock III 59 | 60 | Best Time to Buy and Sell Stock IV 61 | 62 | Best Time to Buy and Sell Stock with Cooldown 63 | */ 64 | -------------------------------------------------------------------------------- /122. Best Time to Buy and Sell Stock II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 122. Best Time to Buy and Sell Stock II 3 | 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 7 | */ 8 | 9 | int maxProfit(int* prices, int pricesSize) { 10 | int i, d, p; 11 | 12 | if (pricesSize < 2) return 0; 13 | 14 | p = 0; 15 | for (i = 1; i < pricesSize; i ++) { 16 | d = prices[i] - prices[i - 1]; 17 | p = d > 0 ? p + d : p; // get it as long as it is a profit! 18 | } 19 | 20 | return p; 21 | } 22 | 23 | 24 | /* 25 | Difficulty:Easy 26 | Total Accepted:152.2K 27 | Total Submissions:323.9K 28 | 29 | 30 | Companies Bloomberg 31 | Related Topics Array Greedy 32 | Similar Questions 33 | 34 | 35 | Best Time to Buy and Sell Stock 36 | 37 | Best Time to Buy and Sell Stock III 38 | 39 | Best Time to Buy and Sell Stock IV 40 | 41 | Best Time to Buy and Sell Stock with Cooldown 42 | */ 43 | -------------------------------------------------------------------------------- /123. Best Time to Buy and Sell Stock III.c: -------------------------------------------------------------------------------- 1 | /* 2 | 123. Best Time to Buy and Sell Stock III 3 | 4 | Say you have an array for which the ith element is the price of a given stock on day i. 5 | 6 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 7 | 8 | Note: 9 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 10 | */ 11 | 12 | int maxProfit(int* prices, int pricesSize) { 13 | int buy1, buy2; // max profit if I buy 14 | int sell1, sell2; // max profit if I sell 15 | int i; 16 | 17 | buy1 = buy2 = 0x80000000; // min of integer 18 | sell1 = sell2 = 0; 19 | 20 | for (i = 0; i < pricesSize; i ++) { 21 | // possible profit 22 | buy1 = buy1 > 0 - prices[i] ? buy1 : 0 - prices[i]; 23 | sell1 = sell1 > buy1 + prices[i] ? sell1 : buy1 + prices[i]; 24 | buy2 = buy2 > sell1 - prices[i] ? buy2 : sell1 - prices[i]; 25 | sell2 = sell2 > buy2 + prices[i] ? sell2 : buy2 + prices[i]; 26 | } 27 | 28 | return sell2; 29 | } 30 | 31 | 32 | /* 33 | Difficulty:Hard 34 | Total Accepted:88.8K 35 | Total Submissions:303.4K 36 | 37 | 38 | Related Topics Array Dynamic Programming 39 | Similar Questions Best Time to Buy and Sell Stock Best Time to Buy and Sell Stock II Best Time to Buy and Sell Stock IV 40 | 41 | */ 42 | -------------------------------------------------------------------------------- /124. Binary Tree Maximum Path Sum.c: -------------------------------------------------------------------------------- 1 | /* 2 | 124. Binary Tree Maximum Path Sum 3 | 4 | Given a binary tree, find the maximum path sum. 5 | 6 | 7 | For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. 8 | 9 | 10 | For example: 11 | Given the below binary tree, 12 | 1 13 | / \ 14 | 2 3 15 | 16 | 17 | 18 | Return 6. 19 | */ 20 | 21 | /** 22 | * Definition for a binary tree node. 23 | * struct TreeNode { 24 | * int val; 25 | * struct TreeNode *left; 26 | * struct TreeNode *right; 27 | * }; 28 | */ 29 | int maxsum(struct TreeNode *node, int *max) { 30 | int l, r, k, s; 31 | 32 | if (!node) return 0; 33 | 34 | l = maxsum(node->left, max); 35 | r = maxsum(node->right, max); 36 | 37 | l = l > 0 ? l : 0; // ignore negative 38 | r = r > 0 ? r : 0; 39 | 40 | s = node->val + l + r; // current node + both sides 41 | if (*max < s) *max = s; 42 | 43 | k = node->val + (l > r ? l : r); // current node + one side only 44 | return k; 45 | } 46 | int maxPathSum(struct TreeNode* root) { 47 | int max; 48 | if (root) { 49 | max = root->val; 50 | maxsum(root, &max); 51 | } else { 52 | max = 0; 53 | } 54 | return max; 55 | } 56 | 57 | 58 | /* 59 | Difficulty:Hard 60 | Total Accepted:101.3K 61 | Total Submissions:388.5K 62 | 63 | 64 | Companies Microsoft Baidu 65 | Related Topics Tree Depth-first Search 66 | Similar Questions 67 | 68 | 69 | Path Sum 70 | 71 | Sum Root to Leaf Numbers 72 | */ 73 | -------------------------------------------------------------------------------- /125. Valid Palindrome.c: -------------------------------------------------------------------------------- 1 | /* 2 | 125. Valid Palindrome 3 | 4 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 5 | 6 | 7 | 8 | For example, 9 | "A man, a plan, a canal: Panama" is a palindrome. 10 | "race a car" is not a palindrome. 11 | 12 | 13 | 14 | Note: 15 | Have you consider that the string might be empty? This is a good question to ask during an interview. 16 | 17 | For the purpose of this problem, we define empty string as valid palindrome. 18 | */ 19 | 20 | bool isPalindrome(char* s) { 21 |    int i = 0; 22 |    int j; 23 |    char a, b; 24 |     25 |    if (!s || !*s) return true; 26 |     27 |    j = strlen(s) - 1; 28 |    while (i < j) { 29 |        a = s[i]; 30 |        b = s[j]; 31 |        if (!((a >= '0' && a <= '9') || 32 |             (a >= 'A' && a <= 'Z') || 33 |             (a >= 'a' && a <= 'z'))) { 34 |            i ++; 35 |            continue; 36 |       } 37 |        if (!((b >= '0' && b <= '9') || 38 |             (b >= 'A' && b <= 'Z') || 39 |             (b >= 'a' && b <= 'z'))) { 40 |            j --; 41 |            continue; 42 |       } 43 |        a = a > 'Z' ? a - 'a' + 'A' : a; 44 |        b = b > 'Z' ? b - 'a' + 'A' : b; 45 |        if (a != b) { 46 |            return false; 47 |       } 48 |        i ++; 49 |        j --; 50 |   } 51 |    return true; 52 | } 53 | 54 | 55 | /* 56 | Difficulty:Easy 57 | Total Accepted:170.9K 58 | Total Submissions:651.4K 59 | 60 | 61 | Companies Microsoft Uber Facebook Zenefits 62 | Related Topics Two Pointers String 63 | Similar Questions 64 | 65 | 66 | Palindrome Linked List 67 | */ 68 | -------------------------------------------------------------------------------- /132. Palindrome Partitioning II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 132. Palindrome Partitioning II 3 | 4 | Given a string s, partition s such that every substring of the partition is a palindrome. 5 | 6 | 7 | Return the minimum cuts needed for a palindrome partitioning of s. 8 | 9 | 10 | For example, given s = "aab", 11 | Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. 12 | */ 13 | 14 | int _min(int a, int b) { 15 | return a < b ? a : b; 16 | } 17 | int minCut(char* s) { 18 | int *dp, n, i, k; 19 | 20 | n = strlen(s); 21 | 22 | dp = malloc((n + 1) * sizeof(int)); // number of cuts on length 23 | //assert(dp); 24 | 25 | dp[0] = -1; 26 | for (i = 0; i < n; i ++) { 27 | dp[i + 1] = dp[i] + 1; 28 | } 29 | 30 | for (i = 0; i < n; i ++) { 31 | dp[i + 1] = _min(dp[i + 1], dp[i] + 1); 32 | 33 | for (k = 1; // "aba" 34 | i - k >= 0 && 35 | i + k < n && 36 | s[i - k] == s[i + k]; 37 | k ++) { 38 | dp[i + k + 1] = _min(dp[i + k + 1], dp[i - k] + 1); 39 | } 40 | 41 | for (k = 1; // "aaaa" 42 | i - k + 1 >= 0 && 43 | i + k < n && 44 | s[i - k + 1] == s[i + k]; 45 | k ++) { 46 | dp[i + k + 1] = _min(dp[i + k + 1], dp[i - k + 1] + 1); 47 | } 48 | } 49 | 50 | i = dp[n]; 51 | 52 | free(dp); 53 | 54 | return i; 55 | } 56 | 57 | 58 | /* 59 | Difficulty:Hard 60 | Total Accepted:71.7K 61 | Total Submissions:296.7K 62 | 63 | 64 | Related Topics Dynamic Programming 65 | Similar Questions Palindrome Partitioning 66 | 67 | */ 68 | -------------------------------------------------------------------------------- /135. Candy.c: -------------------------------------------------------------------------------- 1 | /* 2 | 135. Candy 3 | 4 | There are N children standing in a line. Each child is assigned a rating value. 5 | 6 | 7 | You are giving candies to these children subjected to the following requirements: 8 | 9 | 10 | Each child must have at least one candy. 11 | Children with a higher rating get more candies than their neighbors. 12 | 13 | 14 | What is the minimum candies you must give? 15 | */ 16 | 17 | int candy(int* ratings, int ratingsSize) { 18 | int *candies; 19 | int i, x; 20 | 21 | if (ratingsSize < 2) return ratingsSize; 22 | 23 | candies = malloc(ratingsSize * sizeof(int)); 24 | //assert(candies); 25 | 26 | candies[0] = 1; 27 | for (i = 1; i < ratingsSize; i ++) { 28 | if (ratings[i] > ratings[i - 1]) { 29 | candies[i] = candies[i - 1] + 1; 30 | } else { 31 | candies[i] = 1; 32 | } 33 | } 34 | 35 | x = candies[ratingsSize - 1]; 36 | 37 | for (i = ratingsSize - 2; i >= 0; i --) { 38 | if (ratings[i] > ratings[i + 1]) { 39 | if (candies[i] <= candies[i + 1]) { 40 | candies[i] = candies[i + 1] + 1; 41 | } 42 | } 43 | x += candies[i]; 44 | } 45 | 46 | free(candies); 47 | 48 | return x; 49 | } 50 | 51 | /* 52 | Difficulty:Hard 53 | Total Accepted:70.3K 54 | Total Submissions:284.7K 55 | 56 | 57 | Related Topics Greedy 58 | 59 | */ 60 | -------------------------------------------------------------------------------- /136. Single Number.c: -------------------------------------------------------------------------------- 1 | /* 2 | 136. Single Number 3 | 4 | Given an array of integers, every element appears twice except for one. Find that single one. 5 | 6 | 7 | Note: 8 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 9 | */ 10 | 11 | int singleNumber(int* nums, int numsSize) { 12 |    int i, k = 0; 13 |    for (i = 0; i < numsSize; i ++) { 14 |        k = k ^ nums[i];  // a ^ a equals to 0; 0 ^ a equals to a 15 |   } 16 |    return k; 17 | } 18 | 19 | 20 | /* 21 | Difficulty:Easy 22 | Total Accepted:231K 23 | Total Submissions:424.5K 24 | 25 | 26 | Companies Palantir Airbnb 27 | Related Topics Hash Table Bit Manipulation 28 | Similar Questions 29 | 30 | 31 | Single Number II 32 | 33 | Single Number III 34 | 35 | Missing Number 36 | 37 | Find the Duplicate Number 38 | 39 | Find the Difference 40 | */ 41 | -------------------------------------------------------------------------------- /137. Single Number II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 137. Single Number II 3 | 4 | Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 5 | 6 | 7 | 8 | Note: 9 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 10 | */ 11 | 12 | int singleNumber(int* nums, int numsSize) { 13 |    int i, ones, twos; 14 |    ones = twos = 0; 15 |    for (i = 0; i < numsSize; i ++) { 16 |        ones = (ones ^ nums[i]) & ~twos; 17 |        twos = (twos ^ nums[i]) & ~ones; 18 |   } 19 |    return ones; 20 | } 21 | 22 | 23 | /* 24 | Difficulty:Medium 25 | Total Accepted:119.8K 26 | Total Submissions:288.6K 27 | 28 | 29 | Related Topics Bit Manipulation 30 | Similar Questions Single Number Single Number III 31 | 32 | */ 33 | -------------------------------------------------------------------------------- /14. Longest Common Prefix.c: -------------------------------------------------------------------------------- 1 | /* 2 | 14. Longest Common Prefix 3 | 4 | Write a function to find the longest common prefix string amongst an array of strings. 5 | 6 | If there is no common prefix, return an empty string "". 7 | 8 | Example 1: 9 | 10 | Input: ["flower","flow","flight"] 11 | Output: "fl" 12 | 13 | 14 | Example 2: 15 | 16 | Input: ["dog","racecar","car"] 17 | Output: "" 18 | Explanation: There is no common prefix among the input strings. 19 | 20 | 21 | Note: 22 | 23 | All given inputs are in lowercase letters a-z. 24 | */ 25 | 26 | char* longestCommonPrefix(char** strs, int strsSize) { 27 |    int i, n = 0; 28 |    char c; 29 | 30 |    if (strsSize == 0) return ""; 31 |     32 |    while (c = strs[0][n]) { 33 |        for (i = 1; i < strsSize; i ++) { 34 |            if (strs[i][n] != c) { 35 |                strs[0][n] = 0; 36 |                return strs[0]; 37 |           } 38 |       } 39 |        n ++; 40 |   } 41 |    strs[0][n] = 0; 42 |    return strs[0]; 43 | } 44 | 45 | 46 | /* 47 | Difficulty:Easy 48 | 49 | 50 | */ 51 | -------------------------------------------------------------------------------- /141. Linked List Cycle.c: -------------------------------------------------------------------------------- 1 | /* 2 | 141. Linked List Cycle 3 | 4 | Given a linked list, determine if it has a cycle in it. 5 | 6 | 7 | 8 | Follow up: 9 | Can you solve it without using extra space? 10 | */ 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * struct ListNode { 15 | *     int val; 16 | *     struct ListNode *next; 17 | * }; 18 | */ 19 | bool hasCycle(struct ListNode *head) { 20 |    struct ListNode *n, *nn; 21 |     22 |    if (!head) return false; 23 |     24 |    n = nn = head; 25 |    do { 26 |        n = n->next;            // one step 27 |        nn = nn->next; 28 |        if (nn) nn = nn->next;  // two steps 29 |   } while (nn && n != nn); 30 |     31 |    if (nn) return true; 32 |     33 |    return false; 34 | } 35 | 36 | 37 | /* 38 | Difficulty:Easy 39 | Total Accepted:191.5K 40 | Total Submissions:541.6K 41 | 42 | 43 | Companies Amazon Microsoft Bloomberg Yahoo 44 | Related Topics Linked List Two Pointers 45 | Similar Questions 46 | 47 | 48 | Linked List Cycle II 49 | */ 50 | -------------------------------------------------------------------------------- /142. Linked List Cycle II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 142. Linked List Cycle II 3 | 4 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 5 | 6 | 7 | 8 | Note: Do not modify the linked list. 9 | 10 | 11 | Follow up: 12 | Can you solve it without using extra space? 13 | */ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | *     int val; 19 | *     struct ListNode *next; 20 | * }; 21 | */ 22 | struct ListNode *detectCycle(struct ListNode *head) { 23 |    struct ListNode *n, *nn; 24 |     25 |    if (!head) return NULL; 26 |     27 |    n = nn = head; 28 |    do { 29 |        n = n->next;            // one step 30 |        nn = nn->next; 31 |        if (nn) nn = nn->next;  // two steps 32 |   } while (nn && n != nn); 33 |     34 |    if (!nn) return NULL; 35 |     36 |    // there is a cycle 37 |    n = head; 38 |    while (n != nn) { 39 |        n = n->next; 40 |        nn = nn->next; 41 |   } 42 |     43 |    return n; 44 | } 45 | 46 | 47 | /* 48 | Difficulty:Medium 49 | Total Accepted:119.8K 50 | Total Submissions:386.7K 51 | 52 | 53 | Related Topics Linked List Two Pointers 54 | Similar Questions Linked List Cycle Find the Duplicate Number 55 | 56 | */ 57 | -------------------------------------------------------------------------------- /145. Binary Tree Postorder Traversal.c: -------------------------------------------------------------------------------- 1 | /* 2 | 145. Binary Tree Postorder Traversal 3 | 4 | Given a binary tree, return the postorder traversal of its nodes' values. 5 | 6 | 7 | For example: 8 | Given binary tree {1,#,2,3}, 9 | 1 10 | \ 11 | 2 12 | / 13 | 3 14 | 15 | 16 | 17 | return [3,2,1]. 18 | 19 | 20 | Note: Recursive solution is trivial, could you do it iteratively? 21 | */ 22 | 23 | /** 24 | * Definition for a binary tree node. 25 | * struct TreeNode { 26 | *     int val; 27 | *     struct TreeNode *left; 28 | *     struct TreeNode *right; 29 | * }; 30 | */ 31 | /** 32 | * Return an array of size *returnSize. 33 | * Note: The returned array must be malloced, assume caller calls free(). 34 | */ 35 | void traversal(int **p, int *psz, int *pn, struct TreeNode *node) { 36 |    if (!node) return; 37 |    traversal(p, psz, pn, node->left); 38 |    traversal(p, psz, pn, node->right); 39 |    if (*psz == *pn) { 40 |        *psz *= 2; 41 |        *p = realloc(*p, (*psz) * sizeof(int)); 42 |        //assert(*p); 43 |   } 44 |   (*p)[(*pn) ++] = node->val; 45 | } 46 | int* postorderTraversal(struct TreeNode* root, int* returnSize) { 47 |    int *p, psz, pn; 48 |     49 |    psz = 100; 50 |    p = malloc(psz * sizeof(int)); 51 |    //assert(p); 52 |    pn = 0; 53 |     54 |    traversal(&p, &psz, &pn, root); 55 |     56 |    *returnSize = pn; 57 |     58 |    return p; 59 | } 60 | 61 | 62 | /* 63 | Difficulty:Hard 64 | Total Accepted:147.8K 65 | Total Submissions:368K 66 | 67 | 68 | Related Topics Tree Stack 69 | Similar Questions Binary Tree Inorder Traversal 70 | 71 | */ 72 | -------------------------------------------------------------------------------- /148. Sort List.c: -------------------------------------------------------------------------------- 1 | /* 2 | 148. Sort List 3 | 4 | Sort a linked list in O(n log n) time using constant space complexity. 5 | 6 | Example 1: 7 | 8 | Input: 4->2->1->3 9 | Output: 1->2->3->4 10 | 11 | 12 | Example 2: 13 | 14 | Input: -1->5->3->4->0 15 | Output: -1->0->3->4->5 16 | */ 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * struct ListNode { 21 | * int val; 22 | * struct ListNode *next; 23 | * }; 24 | */ 25 | struct ListNode* divide(struct ListNode *p) { 26 | struct ListNode *a, *b; 27 | a = p; 28 | b = p->next; 29 | 30 | while (b) { 31 | b = b->next; // b moves two steps 32 | if (b) { 33 | a = a->next; // a moves one steps 34 | b = b->next; 35 | } 36 | } 37 | 38 | b = a->next; // this is the middle point 39 | a->next = NULL; 40 | 41 | return b; 42 | } 43 | 44 | struct ListNode* merge(struct ListNode *a, struct ListNode *b) { 45 | struct ListNode head, *p, *c; 46 | 47 | p = &head; 48 | 49 | while (a && b) { 50 | if (a->val < b->val) { 51 | c = a; 52 | a = a->next; 53 | } else { 54 | c = b; 55 | b = b->next; 56 | } 57 | p->next = c; 58 | p = c; 59 | } 60 | 61 | p->next = a ? a : b; 62 | 63 | return head.next; 64 | } 65 | struct ListNode* sortList(struct ListNode* head) { 66 | struct ListNode *p, *a, *b; 67 | 68 | if (!head || !head->next) return head; 69 | 70 | p = divide(head); // divide the list to two 71 | 72 | a = sortList(head); // sort separately 73 | b = sortList(p); 74 | 75 | p = merge(a, b); // and merge them 76 | 77 | return p; 78 | } 79 | 80 | 81 | /* 82 | Difficulty:Medium 83 | 84 | 85 | */ 86 | -------------------------------------------------------------------------------- /152. Maximum Product Subarray.c: -------------------------------------------------------------------------------- 1 | /* 2 | 152. Maximum Product Subarray 3 | 4 | Find the contiguous subarray within an array (containing at least one number) which has the largest product. 5 | 6 | 7 | 8 | For example, given the array [2,3,-2,4], 9 | the contiguous subarray [2,3] has the largest product = 6. 10 | */ 11 | 12 | int maxProduct(int* nums, int numsSize) { 13 |    int i, j, k, m; 14 | #if 0 15 |    // O(n2) 16 |    for (i = 0; i < numsSize; i ++) { 17 |        k = nums[i]; if (i == 0 || m < k) m = k; 18 |        for (j = i + 1; j < numsSize; j ++) { 19 |            k = k * nums[j]; if (m < k) m = k; 20 |       } 21 |   } 22 | #else 23 |    int min, max; 24 |    m = min = max = nums[0]; 25 |    for (i = 1; i < numsSize; i ++) { 26 |        if (nums[i] >= 0) { 27 |            k = max * nums[i]; 28 |            max = k > nums[i] ? k : nums[i]; 29 |            k = min * nums[i]; 30 |            min = k < nums[i] ? k : nums[i]; 31 |       } else { 32 |            j = max; 33 |            k = min * nums[i]; 34 |            max = k > nums[i] ? k : nums[i]; 35 |            k =   j * nums[i]; 36 |            min = k < nums[i] ? k : nums[i]; 37 |       } 38 |        m = m > max ? m : max; 39 |   } 40 | #endif 41 |    return m; 42 | } 43 | 44 | 45 | /* 46 | Difficulty:Medium 47 | Total Accepted:106.6K 48 | Total Submissions:415.3K 49 | 50 | 51 | Companies LinkedIn 52 | Related Topics Array Dynamic Programming 53 | Similar Questions 54 | 55 | 56 | Maximum Subarray 57 | 58 | House Robber 59 | 60 | Product of Array Except Self 61 | 62 | Maximum Product of Three Numbers 63 | */ 64 | -------------------------------------------------------------------------------- /159. Longest Substring with At Most Two Distinct Characters.c: -------------------------------------------------------------------------------- 1 | /* 2 | 159. Longest Substring with At Most Two Distinct Characters 3 | 4 | Given a string, find the length of the longest substring T that contains at most 2 distinct characters. 5 | 6 | 7 | 8 | For example, 9 | 10 | Given s = “eceba”, 11 | 12 | 13 | 14 | T is "ece" which its length is 3. 15 | */ 16 | 17 | int lengthOfLongestSubstringTwoDistinct(char* s) { 18 |    int cnt[128] = { 0 }; 19 |    int head, tail, d = 0; 20 |    char c; 21 |     22 |    int k = 2; 23 |     24 |    head = tail = 0; 25 |    while (s[tail]) { 26 |        while (s[tail] && (cnt[s[tail]] > 0 || k > 0)) { // advance k distinct characters 27 |            if (cnt[s[tail]] == 0) { 28 |                k --;  // reduce number if a new character is counted 29 |           } 30 |            cnt[s[tail]] ++;  // record the count 31 |            tail ++; 32 |       } 33 |         34 |        if (d < tail - head) { 35 |            d = tail - head; 36 |       } 37 |         38 |        do { 39 |            c = s[head ++]; 40 |            cnt[c] --;  // reduce the count 41 |       } while (cnt[c] > 0);  // push out one distinct character from head 42 |         43 |        k = 1;  // find another one distince character from tail 44 |   } 45 |     46 |    return d; 47 | ​ 48 | } 49 | 50 | 51 | /* 52 | Difficulty:Hard 53 | Total Accepted:28K 54 | Total Submissions:68.1K 55 | 56 | 57 | Companies Google 58 | Related Topics Hash Table Two Pointers String 59 | Similar Questions 60 | 61 | 62 | Longest Substring Without Repeating Characters 63 | 64 | Sliding Window Maximum 65 | 66 | Longest Substring with At Most K Distinct Characters 67 | */ 68 | -------------------------------------------------------------------------------- /16. 3Sum Closest.c: -------------------------------------------------------------------------------- 1 | /* 2 | 16. 3Sum Closest 3 | 4 | Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 5 | 6 | For example, given array S = {-1 2 1 -4}, and target = 1. 7 | 8 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 9 | */ 10 | 11 | int cmp(const void *a, const void *b) { 12 |    return *(int *)a - *(int *)b; 13 | } 14 | int threeSumClosest(int* nums, int numsSize, int target) { 15 |    int i, x, y, k, d, d1; 16 |     17 |    qsort(nums, numsSize, sizeof(int), cmp); 18 |     19 |    d = 0; 20 |    for (i = 0; i < numsSize - 2; i ++) { 21 |        x = i + 1; 22 |        y = numsSize - 1; 23 |        while (x < y) { 24 |            k = nums[i] + nums[x] + nums[y]; 25 |            if (k == target) { 26 |                return k; 27 |           } else if (k > target) { 28 |                y --; 29 |           } else { 30 |                x ++; 31 |           } 32 |            d1 = k - target; 33 |            if (d == 0 || abs(d) > abs(d1)) { 34 |                d = d1; 35 |           } 36 |       } 37 |   } 38 |    return target + d; 39 | } 40 | 41 | 42 | /* 43 | Difficulty:Medium 44 | Total Accepted:136.6K 45 | Total Submissions:439.3K 46 | 47 | 48 | Companies Bloomberg 49 | Related Topics Array Two Pointers 50 | Similar Questions 51 | 52 | 53 | 3Sum 54 | 55 | 3Sum Smaller 56 | */ 57 | -------------------------------------------------------------------------------- /160. Intersection of Two Linked Lists.c: -------------------------------------------------------------------------------- 1 | /* 2 | 160. Intersection of Two Linked Lists 3 | 4 | Write a program to find the node at which the intersection of two singly linked lists begins. 5 | 6 | For example, the following two linked lists: 7 | A: a1 → a2 8 | ↘ 9 | c1 → c2 → c3 10 | ↗ 11 | B: b1 → b2 → b3 12 | 13 | begin to intersect at node c1. 14 | 15 | Notes: 16 | 17 | If the two linked lists have no intersection at all, return null. 18 | The linked lists must retain their original structure after the function returns. 19 | You may assume there are no cycles anywhere in the entire linked structure. 20 | Your code should preferably run in O(n) time and use only O(1) memory. 21 | 22 | 23 | 24 | Credits:Special thanks to @stellari for adding this problem and creating all test cases. 25 | */ 26 | 27 | /** 28 | * Definition for singly-linked list. 29 | * struct ListNode { 30 | *     int val; 31 | *     struct ListNode *next; 32 | * }; 33 | */ 34 | struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { 35 |    struct ListNode *a = headA, *b = headB; 36 |     37 |    if (!a || !b) return NULL; 38 |     39 |    while (a != b) { 40 |        a = a ? a->next : headB; 41 |        b = b ? b->next : headA; 42 |   } 43 |     44 |    return a; 45 | } 46 | 47 | 48 | /* 49 | Difficulty:Easy 50 | Total Accepted:140.6K 51 | Total Submissions:460K 52 | 53 | 54 | Companies Amazon Microsoft Bloomberg Airbnb 55 | Related Topics Linked List 56 | Similar Questions 57 | 58 | 59 | Minimum Index Sum of Two Lists 60 | */ 61 | -------------------------------------------------------------------------------- /161. One Edit Distance.c: -------------------------------------------------------------------------------- 1 | /* 2 | 161. One Edit Distance 3 | 4 | Given two strings S and T, determine if they are both one edit distance apart. 5 | */ 6 | 7 | bool isOneEditDistance(char* s, char* t) { 8 |    int sl = strlen(s); 9 |    int tl = strlen(t); 10 |    int i, m; 11 |     12 |    m = sl - tl; 13 |    if (m > 1 || m < -1) return false; 14 |     15 |    for (i = 0; i < sl && i < tl; i ++) { 16 |        if (s[i] == t[i]) continue; 17 |        if (!m) return !strcmp(&s[i + 1], &t[i + 1]); 18 |        if (m > 0) return !strcmp(&s[i + 1], &t[i]); 19 |        return !strcmp(&s[i], &t[i + 1]); 20 |   } 21 |     22 |    return m != 0; 23 | } 24 | 25 | 26 | /* 27 | Difficulty:Medium 28 | Total Accepted:35.4K 29 | Total Submissions:113.4K 30 | 31 | 32 | Companies Snapchat Uber Facebook Twitter 33 | Related Topics String 34 | Similar Questions 35 | 36 | 37 | Edit Distance 38 | */ 39 | -------------------------------------------------------------------------------- /162. Find Peak Element.c: -------------------------------------------------------------------------------- 1 | /* 2 | 162. Find Peak Element 3 | 4 | A peak element is an element that is greater than its neighbors. 5 | 6 | Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. 7 | 8 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 9 | 10 | You may imagine that num[-1] = num[n] = -∞. 11 | 12 | For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. 13 | 14 | click to show spoilers. 15 | 16 | Note: 17 | Your solution should be in logarithmic complexity. 18 | 19 | 20 | Credits:Special thanks to @ts for adding this problem and creating all test cases. 21 | */ 22 | 23 | int findPeakElement(int* nums, int numsSize) { 24 | #if 0 25 |    int i; 26 |     27 |    for (i = 1; i < numsSize && nums[i] > nums[i - 1]; i ++) { 28 |   } 29 |     30 |    return i - 1; 31 | #else 32 |    int l, r, m; 33 |    if (numsSize == 1) return 0; 34 |     35 |    l = 0; r = numsSize - 1; 36 |    while (l < r) { 37 |        m = l + (r - l) / 2; 38 |        if (nums[m] < nums[m + 1]) { 39 |            l = m + 1; 40 |       } else { 41 |            r = m; 42 |       } 43 |   } 44 |     45 |    return l; 46 | #endif 47 | } 48 | 49 | 50 | /* 51 | Difficulty:Medium 52 | Total Accepted:119.1K 53 | Total Submissions:318.1K 54 | 55 | 56 | Companies Microsoft Google 57 | Related Topics Binary Search Array 58 | 59 | */ 60 | -------------------------------------------------------------------------------- /165. Compare Version Numbers.c: -------------------------------------------------------------------------------- 1 | /* 2 | 165. Compare Version Numbers 3 | 4 | Compare two version numbers version1 and version2. 5 | If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. 6 | 7 | You may assume that the version strings are non-empty and contain only digits and the . character. 8 | The . character does not represent a decimal point and is used to separate number sequences. 9 | For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. 10 | 11 | Here is an example of version numbers ordering: 12 | 0.1 < 1.1 < 1.2 < 13.37 13 | 14 | Credits:Special thanks to @ts for adding this problem and creating all test cases. 15 | */ 16 | 17 | int compareVersion(char* version1, char* version2) { 18 |    int a, b; 19 |    char *v1, *v2; 20 |    while (version1 || version2) { 21 |        if (version1) { 22 |            v1 = version1; 23 |            version1 = strchr(version1, '.'); 24 |            if (version1) { 25 |                *version1 = 0; 26 |                version1 ++; 27 |           } 28 |            a = atoi(v1); 29 |       } else { 30 |            a = 0; 31 |       } 32 |        if (version2) { 33 |            v2 = version2; 34 |            version2 = strchr(version2, '.'); 35 |            if (version2) { 36 |                *version2 = 0; 37 |                version2 ++; 38 |           } 39 |            b = atoi(v2); 40 |       } else { 41 |            b = 0; 42 |       } 43 |        if (a > b) return 1; 44 |        if (a < b) return -1; 45 |   } 46 |     47 |    return 0; 48 | } 49 | 50 | 51 | /* 52 | Difficulty:Medium 53 | Total Accepted:86.5K 54 | Total Submissions:431.1K 55 | 56 | 57 | Companies Microsoft Apple 58 | Related Topics String 59 | 60 | */ 61 | -------------------------------------------------------------------------------- /167. Two Sum II - Input array is sorted.c: -------------------------------------------------------------------------------- 1 | /* 2 | 167. Two Sum II - Input array is sorted 3 | 4 | Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 5 | 6 | The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. 7 | 8 | You may assume that each input would have exactly one solution and you may not use the same element twice. 9 | 10 | 11 | Input: numbers={2, 7, 11, 15}, target=9 12 | Output: index1=1, index2=2 13 | */ 14 | 15 | /** 16 | * Return an array of size *returnSize. 17 | * Note: The returned array must be malloced, assume caller calls free(). 18 | */ 19 | int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) { 20 |    int *result; 21 |    int i, j, total; 22 | ​ 23 |    result = malloc(2 * sizeof(int)); 24 |    //assert(result); 25 | ​ 26 |    *returnSize = 0; 27 | ​ 28 |    i = 0; 29 |    j = numbersSize - 1; 30 |    while (i < j) { 31 |        total = numbers[i] + numbers[j]; 32 |        if (total > target) { 33 |            j --; 34 |       } else if (total < target) { 35 |            i ++; 36 |       } else { 37 |            result[0] = i + 1; 38 |            result[1] = j + 1; 39 |            *returnSize = 2; 40 |            break; 41 |       } 42 |   } 43 | ​ 44 |    return result; 45 | } 46 | 47 | 48 | /* 49 | Difficulty:Easy 50 | Total Accepted:90.5K 51 | Total Submissions:192.5K 52 | 53 | 54 | Companies Amazon 55 | Related Topics Array Two Pointers Binary Search 56 | Similar Questions 57 | 58 | 59 | Two Sum 60 | 61 | Two Sum IV - Input is a BST 62 | */ 63 | -------------------------------------------------------------------------------- /168. Excel Sheet Column Title.c: -------------------------------------------------------------------------------- 1 | /* 2 | 168. Excel Sheet Column Title 3 | 4 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 5 | 6 | For example: 7 | 1 -> A 8 | 2 -> B 9 | 3 -> C 10 | ... 11 | 26 -> Z 12 | 27 -> AA 13 | 28 -> AB 14 | 15 | Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. 16 | */ 17 | 18 | char* convertToTitle(int n) { 19 |    char *s; 20 |    int sz, l, k; 21 |    int i, j; 22 |     23 |    sz = 100; 24 |    s = malloc(sz * sizeof(char)); 25 |    //assert(s); 26 |    l = 0; 27 |    while (n) { 28 |        if (sz == l) { 29 |            sz *= 2; 30 |            s = realloc(s, sz * sizeof(char)); 31 |            //assert(s); 32 |       } 33 |        k = (n - 1) % 26; 34 |        s[l ++] = 'A' + k; 35 |        n = (n - 1) / 26; 36 |   } 37 |    s[l] = 0; 38 |    for (i = 0, j = l - 1; i < j; i ++, j --) { 39 |        k = s[i]; 40 |        s[i] = s[j]; 41 |        s[j] = k; 42 |   } 43 |    return s; 44 | } 45 | 46 | 47 | /* 48 | Difficulty:Easy 49 | Total Accepted:107.7K 50 | Total Submissions:414.9K 51 | 52 | 53 | Companies Microsoft Facebook Zenefits 54 | Related Topics Math 55 | Similar Questions 56 | 57 | 58 | Excel Sheet Column Number 59 | */ 60 | -------------------------------------------------------------------------------- /171. Excel Sheet Column Number.c: -------------------------------------------------------------------------------- 1 | /* 2 | 171. Excel Sheet Column Number 3 | 4 | Related to question Excel Sheet Column Title 5 | Given a column title as appear in an Excel sheet, return its corresponding column number. 6 | 7 | For example: 8 | A -> 1 9 | B -> 2 10 | C -> 3 11 | ... 12 | Z -> 26 13 | AA -> 27 14 | AB -> 28 15 | 16 | Credits:Special thanks to @ts for adding this problem and creating all test cases. 17 | */ 18 | 19 | int titleToNumber(char* s) { 20 |    int k = 0; 21 |    while (s && *s) { 22 |        k = k * 26 + (*s) - 'A' + 1; 23 |        s ++; 24 |   } 25 |    return k; 26 | } 27 | 28 | 29 | /* 30 | Difficulty:Easy 31 | Total Accepted:136.5K 32 | Total Submissions:289.8K 33 | 34 | 35 | Companies Microsoft Uber 36 | Related Topics Math 37 | Similar Questions 38 | 39 | 40 | Excel Sheet Column Title 41 | */ 42 | -------------------------------------------------------------------------------- /186. Reverse Words in a String II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 186. Reverse Words in a String II 3 | 4 | Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. 5 | 6 | 7 | 8 | The input string does not contain leading or trailing spaces and the words are always separated by a single space. 9 | 10 | 11 | 12 | For example, 13 | Given s = "the sky is blue", 14 | return "blue is sky the". 15 | 16 | 17 | 18 | Could you do it in-place without allocating extra space? 19 | 20 | 21 | Related problem: Rotate Array 22 | */ 23 | 24 | void swap(char *a, char *b) { 25 |    char c = *a; 26 |    *a = *b; 27 |    *b = c; 28 | } 29 | void reverse(char *s, int start, int end, int w) { 30 |    int i, j; 31 |     32 |    for (i = start, j = end; i <= j; i ++, j --) { 33 |        swap(&s[i], &s[j]); 34 |        if (w && s[i] == ' ') { 35 |            reverse(s, start, i - 1, 0); 36 |            start = i + 1; 37 |        } 38 |        if (w && s[j] == ' ') { 39 |            reverse(s, j + 1, end, 0); 40 |            end = j - 1; 41 |       } 42 |   } 43 |     44 |    if (w && start < end) reverse(s, start, end, 0); 45 | } 46 | void reverseWords(char *s) { 47 |    reverse(s, 0, strlen(s) - 1, 1); 48 | } 49 | 50 | 51 | /* 52 | Difficulty:Medium 53 | Total Accepted:30.2K 54 | Total Submissions:110.3K 55 | 56 | 57 | Companies Microsoft Amazon Uber 58 | Related Topics String 59 | Similar Questions 60 | 61 | 62 | Reverse Words in a String 63 | 64 | Rotate Array 65 | */ 66 | -------------------------------------------------------------------------------- /19. Remove Nth Node From End of List.c: -------------------------------------------------------------------------------- 1 | /* 2 | 19. Remove Nth Node From End of List 3 | 4 | Given a linked list, remove the nth node from the end of list and return its head. 5 | 6 | 7 | For example, 8 | 9 | Given linked list: 1->2->3->4->5, and n = 2. 10 | 11 | After removing the second node from the end, the linked list becomes 1->2->3->5. 12 | 13 | 14 | 15 | Note: 16 | Given n will always be valid. 17 | Try to do this in one pass. 18 | */ 19 | 20 | /** 21 | * Definition for singly-linked list. 22 | * struct ListNode { 23 | * int val; 24 | * struct ListNode *next; 25 | * }; 26 | */ 27 | struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { 28 | struct ListNode *a, *b, *p = NULL; 29 | a = b = head; 30 | while (n-- > 0) { // b moves n steps first 31 | b = b->next; 32 | } 33 | 34 | while (b) { // a, b move together, keeps a gap of n steps 35 | p = a; 36 | a = a->next; 37 | b = b->next; 38 | } 39 | 40 | if (a == head) { // a is the one to be removed 41 | head = a->next; 42 | } else { 43 | p->next = a->next; 44 | } 45 | free(a); 46 | 47 | return head; 48 | } 49 | 50 | 51 | /* 52 | Difficulty:Medium 53 | Total Accepted:188.5K 54 | Total Submissions:563.1K 55 | 56 | 57 | Related Topics Linked List Two Pointers 58 | 59 | */ 60 | -------------------------------------------------------------------------------- /190. Reverse Bits.c: -------------------------------------------------------------------------------- 1 | /* 2 | 190. Reverse Bits 3 | 4 | Reverse bits of a given 32 bits unsigned integer. 5 | 6 | For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 7 | 8 | 9 | Follow up: 10 | If this function is called many times, how would you optimize it? 11 | 12 | 13 | Related problem: Reverse Integer 14 | 15 | Credits:Special thanks to @ts for adding this problem and creating all test cases. 16 | */ 17 | 18 | uint32_t reverseBits(uint32_t n) { 19 | /* 20 | uint32_t k, i; 21 | k = 0; 22 | for (i = 0; i < 32; i ++) { 23 | k = (k << 1) | (n & 1); 24 | n = n >> 1; 25 | } 26 | return k; 27 | */ 28 | n = ((n & 0xffff0000) >> 16) | ((n & 0x0000ffff) << 16); 29 | n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8); 30 | n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4); 31 | n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2); 32 | n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1); 33 | 34 | return n; 35 | } 36 | 37 | 38 | /* 39 | Difficulty:Easy 40 | Total Accepted:109.3K 41 | Total Submissions:370.1K 42 | 43 | 44 | Companies Apple Airbnb 45 | Related Topics Bit Manipulation 46 | Similar Questions 47 | 48 | 49 | Number of 1 Bits 50 | */ 51 | -------------------------------------------------------------------------------- /191. Number of 1 Bits.c: -------------------------------------------------------------------------------- 1 | /* 2 | 191. Number of 1 Bits 3 | 4 | Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 5 | 6 | For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 7 | 8 | Credits:Special thanks to @ts for adding this problem and creating all test cases. 9 | */ 10 | 11 | int helper(uint32_t n, uint32_t b) { 12 | uint64_t k; 13 | 14 | if (n == 0) return 0; 15 | 16 | k = ((uint64_t)1 << b) - 1; 17 | 18 | if (n == k) return b; 19 | 20 | b >>= 1; 21 | 22 | return helper(n >> b, b) + 23 | helper(n & ((1 << b) - 1), b); 24 | } 25 | int hammingWeight(uint32_t n) { 26 | #if 0 27 | int c = 0; 28 | while (n) { 29 | c ++; 30 | n &= (n - 1); 31 | } 32 | return c; 33 | #else 34 | return helper(n, 32); 35 | #endif 36 | } 37 | 38 | 39 | /* 40 | Difficulty:Easy 41 | Total Accepted:158K 42 | Total Submissions:399.2K 43 | 44 | 45 | Companies Microsoft Apple 46 | Related Topics Bit Manipulation 47 | Similar Questions 48 | 49 | 50 | Reverse Bits 51 | 52 | Power of Two 53 | 54 | Counting Bits 55 | 56 | Binary Watch 57 | 58 | Hamming Distance 59 | */ 60 | -------------------------------------------------------------------------------- /20. Valid Parentheses.c: -------------------------------------------------------------------------------- 1 | /* 2 | 20. Valid Parentheses 3 | 4 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | 6 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 7 | */ 8 | 9 | bool isValid(char* s) { 10 | int l; 11 | char *stack, c; 12 | int sp = 0; 13 | 14 | if (!s || !*s) return true; 15 | 16 | l = strlen(s); 17 | stack = malloc(l * sizeof(char)); 18 | //assert(stack); 19 | while (c = *s ++) { 20 | switch (c) { 21 | case '(': 22 | case '{': 23 | case '[': 24 | stack[sp ++] = c; 25 | break; 26 | case ')': 27 | if (sp == 0 || stack[-- sp] != '(') { free(stack); return false; } 28 | break; 29 | case '}': 30 | if (sp == 0 || stack[-- sp] != '{') { free(stack); return false; } 31 | break; 32 | case ']': 33 | if (sp == 0 || stack[-- sp] != '[') { free(stack); return false; } 34 | break; 35 | default: 36 | break; 37 | } 38 | } 39 | 40 | free(stack); 41 | return sp == 0 ? true : false; 42 | } 43 | 44 | 45 | /* 46 | Difficulty:Easy 47 | Total Accepted:224.5K 48 | Total Submissions:672.8K 49 | 50 | 51 | Companies Google Airbnb Facebook Twitter Zenefits Amazon Microsoft Bloomberg 52 | Related Topics Stack String 53 | Similar Questions 54 | 55 | 56 | Generate Parentheses 57 | 58 | Longest Valid Parentheses 59 | 60 | Remove Invalid Parentheses 61 | */ 62 | -------------------------------------------------------------------------------- /205. Isomorphic Strings.c: -------------------------------------------------------------------------------- 1 | /* 2 | 205. Isomorphic Strings 3 | 4 | Given two strings s and t, determine if they are isomorphic. 5 | 6 | Two strings are isomorphic if the characters in s can be replaced to get t. 7 | 8 | All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 9 | 10 | For example, 11 | Given "egg", "add", return true. 12 | 13 | Given "foo", "bar", return false. 14 | 15 | Given "paper", "title", return true. 16 | 17 | Note: 18 | You may assume both s and t have the same length. 19 | */ 20 | 21 | bool isIsomorphic(char* s, char* t) { 22 |    char a[128] = { 0 }; 23 |    char b[128] = { 0 }; 24 |    while (*s) { 25 |        //printf("%c:%c\n", *s, *t); 26 |        if (a[*s] == 0 && b[*t] == 0) { 27 |            a[*s] = *t; 28 |            b[*t] = *s; 29 |       } else if (a[*s] == *t && b[*t] == *s) { 30 |       } else { 31 |            return false; 32 |       } 33 |        s ++; 34 |        t ++; 35 |   } 36 |    return true; 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Easy 42 | Total Accepted:110.2K 43 | Total Submissions:326.3K 44 | 45 | 46 | Companies LinkedIn 47 | Related Topics Hash Table 48 | Similar Questions 49 | 50 | 51 | Word Pattern 52 | */ 53 | -------------------------------------------------------------------------------- /206. Reverse Linked List.c: -------------------------------------------------------------------------------- 1 | /* 2 | 206. Reverse Linked List 3 | 4 | Reverse a singly linked list. 5 | 6 | click to show more hints. 7 | 8 | Hint: 9 | A linked list can be reversed either iteratively or recursively. Could you implement both? 10 | */ 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * struct ListNode { 15 | *     int val; 16 | *     struct ListNode *next; 17 | * }; 18 | */ 19 | struct ListNode* reverseList(struct ListNode* head) { 20 |    struct ListNode *a, *b, *c; 21 |     22 |    a = NULL; 23 |    b = head; 24 |    while (b) { 25 |        c = b->next; 26 |        b->next = a; 27 |        a = b; 28 |        b = c; 29 |   } 30 | ​ 31 |    return a; 32 | } 33 | 34 | 35 | /* 36 | Difficulty:Easy 37 | Total Accepted:245.8K 38 | Total Submissions:541.6K 39 | 40 | 41 | Companies Uber Facebook Twitter Zenefits Amazon Microsoft Snapchat Apple Yahoo Bloomberg Yelp Adobe 42 | Related Topics Linked List 43 | Similar Questions 44 | 45 | 46 | Reverse Linked List II 47 | 48 | Binary Tree Upside Down 49 | 50 | Palindrome Linked List 51 | */ 52 | -------------------------------------------------------------------------------- /209. Minimum Size Subarray Sum.c: -------------------------------------------------------------------------------- 1 | /* 2 | 209. Minimum Size Subarray Sum 3 | 4 | Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. 5 | 6 | 7 | For example, given the array [2,3,1,2,4,3] and s = 7, 8 | the subarray [4,3] has the minimal length under the problem constraint. 9 | 10 | 11 | click to show more practice. 12 | 13 | More practice: 14 | 15 | If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 16 | 17 | 18 | Credits:Special thanks to @Freezen for adding this problem and creating all test cases. 19 | */ 20 | 21 | int minSubArrayLen(int s, int* nums, int numsSize) { 22 |    int i, j, k, d = 0; 23 |     24 |    k = 0; 25 |    for (i = 0, j = 0; i < numsSize; i ++) { 26 |        k += nums[i]; 27 |        while (k >= s) { 28 |            // found it 29 |            if (d == 0 || d > i - j + 1) { 30 |                d = i - j + 1; 31 |           } 32 |            // try to shrink the window from left pointer 33 |            k -= nums[j ++]; 34 |       } 35 |   } 36 |     37 |    return d; 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Medium 43 | Total Accepted:88.2K 44 | Total Submissions:288.4K 45 | 46 | 47 | Companies Facebook 48 | Related Topics Array Two Pointers Binary Search 49 | Similar Questions 50 | 51 | 52 | Minimum Window Substring 53 | 54 | Maximum Size Subarray Sum Equals k 55 | */ 56 | -------------------------------------------------------------------------------- /21. Merge Two Sorted Lists.c: -------------------------------------------------------------------------------- 1 | /* 2 | 21. Merge Two Sorted Lists 3 | 4 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 5 | */ 6 | 7 | /** 8 | * Definition for singly-linked list. 9 | * struct ListNode { 10 | *     int val; 11 | *     struct ListNode *next; 12 | * }; 13 | */ 14 | struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { 15 |    struct ListNode head, *p; 16 |     17 |    p = &head; 18 |     19 |    while (l1 && l2) { 20 |        if (l1->val <= l2->val) { 21 |            p->next = l1; 22 |            l1 = l1->next; 23 |       } else { 24 |            p->next = l2; 25 |            l2 = l2->next; 26 |       } 27 |        p = p->next; 28 |   } 29 |     30 |    // chain remaining 31 |    if (l1) p->next = l1; 32 |    if (l2) p->next = l2; 33 |     34 |    p = head.next; 35 |     36 |    return p; 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Easy 42 | Total Accepted:244K 43 | Total Submissions:624.7K 44 | 45 | 46 | Companies Amazon LinkedIn Apple Microsoft 47 | Related Topics Linked List 48 | Similar Questions 49 | 50 | 51 | Merge k Sorted Lists 52 | 53 | Merge Sorted Array 54 | 55 | Sort List 56 | 57 | Shortest Word Distance II 58 | */ 59 | -------------------------------------------------------------------------------- /214. Shortest Palindrome.c: -------------------------------------------------------------------------------- 1 | /* 2 | 214. Shortest Palindrome 3 | 4 | Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. 5 | 6 | 7 | For example: 8 | Given "aacecaaa", return "aaacecaaa". 9 | Given "abcd", return "dcbabcd". 10 | 11 | Credits:Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases. 12 | */ 13 | 14 | char* shortestPalindrome(char* s) { 15 | // two pointers, head and tail 16 | // verify if it is a valid palindrome 17 | // if not, reduce tail pointer and repeat verify 18 | // if yes, stop verify 19 | // add characters from end to the tail pointer to a buffer 20 | // append characters from head to tail to the buffer 21 | // done 22 | return s; 23 | } 24 | 25 | 26 | /* 27 | Difficulty:Hard 28 | Total Accepted:41.7K 29 | Total Submissions:172.4K 30 | 31 | 32 | Companies Pocket Gems Google 33 | Related Topics String 34 | Similar Questions 35 | 36 | 37 | Longest Palindromic Substring 38 | 39 | Implement strStr() 40 | 41 | Palindrome Pairs 42 | */ 43 | -------------------------------------------------------------------------------- /217. Contains Duplicate.c: -------------------------------------------------------------------------------- 1 | /* 2 | 217. Contains Duplicate 3 | 4 | Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 5 | */ 6 | 7 | int cmp(const void *a, const void *b) { 8 |    return *(int *)a - *(int *)b; 9 | } 10 | bool containsDuplicate(int* nums, int numsSize) { 11 |    int i; 12 |     13 |    qsort(nums, numsSize, sizeof(int), cmp); 14 |     15 |    for (i = 1; i < numsSize; i ++) { 16 |        if (nums[i] == nums[i - 1]) return true; 17 |   } 18 |     19 |    return false; 20 | } 21 | 22 | 23 | /* 24 | Difficulty:Easy 25 | Total Accepted:168.7K 26 | Total Submissions:368.9K 27 | 28 | 29 | Companies Palantir Airbnb Yahoo 30 | Related Topics Array Hash Table 31 | Similar Questions 32 | 33 | 34 | Contains Duplicate II 35 | 36 | Contains Duplicate III 37 | */ 38 | -------------------------------------------------------------------------------- /219. Contains Duplicate II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 219. Contains Duplicate II 3 | 4 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 5 | */ 6 | 7 | typedef struct { 8 |    int val; 9 |    int idx; 10 | } e_t; 11 | int cmp(void const *a, void const *b) { 12 |    return ((const e_t *)a)->val < ((const e_t *)b)->val ? -1 : 13 |           ((const e_t *)a)->val > ((const e_t *)b)->val ?  1 : 14 |           ((const e_t *)a)->idx < ((const e_t *)b)->idx ? -1 : 1; 15 | } 16 | bool containsNearbyDuplicate(int* nums, int numsSize, int k) { 17 |    e_t *p; 18 |    int i, f; 19 |     20 |    p = malloc(numsSize * sizeof(e_t)); 21 |    //assert(p); 22 |    for (i = 0; i < numsSize; i ++) { 23 |        p[i].val = nums[i]; 24 |        p[i].idx = i; 25 |   } 26 |     27 |    qsort(p, numsSize, sizeof(e_t), cmp); 28 |     29 |    f = 0; 30 |    for (i = 1; !f && i < numsSize; i ++) { 31 |        if (p[i].val == p[i - 1].val && 32 |            p[i].idx - p[i - 1].idx <= k) f = 1; 33 |   } 34 |     35 |    free(p); 36 |     37 |    return f; 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Easy 43 | Total Accepted:116.5K 44 | Total Submissions:360K 45 | 46 | 47 | Companies Palantir Airbnb 48 | Related Topics Array Hash Table 49 | Similar Questions 50 | 51 | 52 | Contains Duplicate 53 | 54 | Contains Duplicate III 55 | */ 56 | -------------------------------------------------------------------------------- /221. Maximal Square.c: -------------------------------------------------------------------------------- 1 | /* 2 | 221. Maximal Square 3 | 4 | Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 5 | 6 | 7 | For example, given the following matrix: 8 | 1 0 1 0 0 9 | 1 0 1 1 1 10 | 1 1 1 1 1 11 | 1 0 0 1 0 12 | 13 | Return 4. 14 | 15 | 16 | Credits:Special thanks to @Freezen for adding this problem and creating all test cases. 17 | */ 18 | 19 | int test_square(char **matrix, int row, int col, int k) { 20 |    int x; 21 |    for (x = 0; x <= k; x ++) { 22 |        if (matrix[row + x][col + k] == '0' || 23 |            matrix[row + k][col + x] == '0') return 0; 24 |   } 25 |    return 1; 26 | } 27 | int maximalSquare(char** matrix, int matrixRowSize, int matrixColSize) { 28 |    int max = 0; 29 |    int i, j, k; 30 |    for (i = 0; i < matrixRowSize; i ++) { 31 |        for (j = 0; j < matrixColSize; j ++) { 32 |            k = 0; 33 |            while (i + k < matrixRowSize && 34 |                   j + k < matrixColSize && 35 |                   test_square(matrix, i, j, k)) { 36 |                k ++; 37 |           } 38 |            max = max < k ? k : max; 39 |       } 40 |   } 41 |    return max * max; 42 | } 43 | 44 | 45 | /* 46 | Difficulty:Medium 47 | Total Accepted:65.3K 48 | Total Submissions:226.4K 49 | 50 | 51 | Companies Apple Airbnb Facebook 52 | Related Topics Dynamic Programming 53 | Similar Questions 54 | 55 | 56 | Maximal Rectangle 57 | */ 58 | -------------------------------------------------------------------------------- /222. Count Complete Tree Nodes.c: -------------------------------------------------------------------------------- 1 | /* 2 | 222. Count Complete Tree Nodes 3 | 4 | Given a complete binary tree, count the number of nodes. 5 | 6 | Definition of a complete binary tree from Wikipedia: 7 | In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. 8 | */ 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * struct TreeNode { 13 | * int val; 14 | * struct TreeNode *left; 15 | * struct TreeNode *right; 16 | * }; 17 | */ 18 | void dfs(struct TreeNode *node, int i, int n, int *x) { 19 | if (i == n) { 20 | if (node->left) (*x) ++; 21 | if (node->right) (*x) ++; 22 | return; 23 | } 24 | 25 | if ((*x) % 2) return; 26 | dfs(node->left, i + 1, n, x); 27 | 28 | if ((*x) % 2) return; 29 | dfs(node->right, i + 1, n, x); 30 | } 31 | int countNodes(struct TreeNode* root) { 32 | struct TreeNode *node = root; 33 | int i = 0; 34 | int x = 0; 35 | 36 | if (!node) return 0; 37 | 38 | while (node) { 39 | i ++; 40 | node = node->right; 41 | } 42 | 43 | dfs(root, 1, i, &x); 44 | 45 | return (1 << i) - 1 + x; 46 | } 47 | 48 | 49 | /* 50 | Difficulty:Medium 51 | Total Accepted:64.8K 52 | Total Submissions:235.8K 53 | 54 | 55 | Related Topics Tree Binary Search 56 | Similar Questions Closest Binary Search Tree Value 57 | 58 | */ 59 | -------------------------------------------------------------------------------- /223. Rectangle Area.c: -------------------------------------------------------------------------------- 1 | /* 2 | 223. Rectangle Area 3 | 4 | Find the total area covered by two rectilinear rectangles in a 2D plane. 5 | Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 6 | 7 | 8 | 9 | 10 | Assume that the total area is never beyond the maximum possible value of int. 11 | 12 | 13 | Credits:Special thanks to @mithmatt for adding this problem, creating the above image and all test cases. 14 | */ 15 | 16 | int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 17 |    int a, b, c, d, e, f, g, h; 18 |    int dup; 19 |    int x, y; 20 |    if (A < E) { 21 |        a = A; b = B; c = C; d = D; 22 |        e = E; f = F; g = G; h = H; 23 |   } else { 24 |        a = E; b = F; c = G; d = H; 25 |        e = A; f = B; g = C; h = D; 26 |   } 27 |    if (h < b || f > d || e > c) { 28 |        dup = 0; 29 |   } else { 30 |        x = c < g ? c - e : g - e; 31 |        y = d < h ? d - (b > f ? b : f) : h - (b > f ? b : f); 32 |        dup = x * y; 33 |   } 34 |    return (c - a) * (d - b) + (g - e) * (h - f) - dup; 35 | } 36 | 37 | 38 | /* 39 | Difficulty:Medium 40 | Total Accepted:63.1K 41 | Total Submissions:191.8K 42 | 43 | 44 | Related Topics Math 45 | 46 | */ 47 | -------------------------------------------------------------------------------- /230. Kth Smallest Element in a BST.c: -------------------------------------------------------------------------------- 1 | /* 2 | 230. Kth Smallest Element in a BST 3 | 4 | Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 5 | 6 | Note: 7 | You may assume k is always valid, 1 ? k ? BST's total elements. 8 | 9 | Follow up: 10 | What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? 11 | 12 | Credits:Special thanks to @ts for adding this problem and creating all test cases. 13 | */ 14 | 15 | /** 16 | * Definition for a binary tree node. 17 | * struct TreeNode { 18 | *     int val; 19 | *     struct TreeNode *left; 20 | *     struct TreeNode *right; 21 | * }; 22 | */ 23 | int count(struct TreeNode *node) { 24 |    if (!node) return 0; 25 |    return count(node->left) + count(node->right) + 1; 26 | } 27 | int kthSmallest(struct TreeNode* root, int k) { 28 |    struct TreeNode *node = root; 29 |    int n; 30 |    n = count(node->left); 31 |    if (n == k - 1) { 32 |        return node->val; 33 |   } else 34 |    if (n >= k) { 35 |        return kthSmallest(node->left, k); 36 |   } 37 |    return kthSmallest(node->right, k - n - 1); 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Medium 43 | Total Accepted:104.8K 44 | Total Submissions:239.5K 45 | 46 | 47 | Companies Bloomberg Uber Google 48 | Related Topics Binary Search Tree 49 | Similar Questions 50 | 51 | 52 | Binary Tree Inorder Traversal 53 | */ 54 | -------------------------------------------------------------------------------- /231. Power of Two.c: -------------------------------------------------------------------------------- 1 | /* 2 | 231. Power of Two 3 | 4 | Given an integer, write a function to determine if it is a power of two. 5 | 6 | 7 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 8 | */ 9 | 10 | bool isPowerOfTwo(int n) { 11 |    if (!n || (n & 0x80000000)) return false; // this is important! 12 | #if 0 13 |    while (!(n & 1)) n >>= 1; 14 |    return n == 1 ? true : false; 15 | #else 16 |    //printf("%x, %x\n", n, n - 1); 17 |    return (n & (n - 1)) == 0 ? true : false; 18 | #endif 19 | } 20 | 21 | 22 | /* 23 | Difficulty:Easy 24 | Total Accepted:141.5K 25 | Total Submissions:352.5K 26 | 27 | 28 | Companies Google 29 | Related Topics Math Bit Manipulation 30 | Similar Questions 31 | 32 | 33 | Number of 1 Bits 34 | 35 | Power of Three 36 | 37 | Power of Four 38 | */ 39 | -------------------------------------------------------------------------------- /234. Palindrome Linked List.c: -------------------------------------------------------------------------------- 1 | /* 2 | 234. Palindrome Linked List 3 | 4 | Given a singly linked list, determine if it is a palindrome. 5 | 6 | Follow up: 7 | Could you do it in O(n) time and O(1) space? 8 | */ 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * struct ListNode { 13 | *     int val; 14 | *     struct ListNode *next; 15 | * }; 16 | */ 17 | bool isPalindrome(struct ListNode* head) { 18 |    struct ListNode *fast, *slow; 19 |    struct ListNode *half = NULL, *tail = NULL; 20 |    struct ListNode *p; 21 |     22 |    fast = slow = head; 23 |    while (fast && fast->next && fast->next->next) { 24 |        fast = fast->next->next; 25 |        slow = slow->next; 26 |   } 27 |     28 |    if (fast && fast->next) { 29 |        half = slow->next; 30 |   } else { 31 |        half = slow; 32 |   } 33 |     34 |    while (half) { 35 |        p = half->next; 36 |        half->next = tail; 37 |        tail = half; 38 |        half = p; 39 |   } 40 |     41 |    while (tail) { 42 |        if (tail->val != head->val) return false; 43 |        tail = tail->next; 44 |        head = head->next; 45 |   } 46 |     47 |    return true; 48 | } 49 | 50 | 51 | /* 52 | Difficulty:Easy 53 | Total Accepted:113.4K 54 | Total Submissions:346.7K 55 | 56 | 57 | Companies Amazon Facebook 58 | Related Topics Linked List Two Pointers 59 | Similar Questions 60 | 61 | 62 | Palindrome Number 63 | 64 | Valid Palindrome 65 | 66 | Reverse Linked List 67 | */ 68 | -------------------------------------------------------------------------------- /235. Lowest Common Ancestor of a Binary Search Tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | 235. Lowest Common Ancestor of a Binary Search Tree 3 | 4 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 5 | 6 | 7 | 8 | According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” 9 | 10 | 11 | _______6______ 12 | / \ 13 | ___2__ ___8__ 14 | / \ / \ 15 | 0 _4 7 9 16 | / \ 17 | 3 5 18 | 19 | 20 | 21 | For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. 22 | */ 23 | 24 | /** 25 | * Definition for a binary tree node. 26 | * struct TreeNode { 27 | *     int val; 28 | *     struct TreeNode *left; 29 | *     struct TreeNode *right; 30 | * }; 31 | */ 32 | struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { 33 |    if (root == NULL) { 34 |        return NULL; 35 |   } 36 |    if (root->val > p->val && root->val > q->val) { 37 |        return lowestCommonAncestor(root->left, p, q); 38 |   } 39 |    if (root->val < p->val && root->val < q->val) { 40 |        return lowestCommonAncestor(root->right, p, q); 41 |   } 42 |    return root; 43 | } 44 | 45 | 46 | /* 47 | Difficulty:Easy 48 | Total Accepted:148.3K 49 | Total Submissions:380.4K 50 | 51 | 52 | Companies Amazon Microsoft Facebook Twitter 53 | Related Topics Tree 54 | Similar Questions 55 | 56 | 57 | Lowest Common Ancestor of a Binary Tree 58 | */ 59 | -------------------------------------------------------------------------------- /237. Delete Node in a Linked List.c: -------------------------------------------------------------------------------- 1 | /* 2 | 237. Delete Node in a Linked List 3 | 4 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 5 | 6 | 7 | 8 | Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 9 | */ 10 | 11 | /** 12 | * Definition for singly-linked list. 13 | * struct ListNode { 14 | *     int val; 15 | *     struct ListNode *next; 16 | * }; 17 | */ 18 | void deleteNode(struct ListNode* node) { 19 |    struct ListNode *p; 20 |     21 |    if (!node || !node->next) return; 22 |     23 |    p = node->next; 24 |    *node = *p; 25 |    free(p); 26 | } 27 | 28 | 29 | /* 30 | Difficulty:Easy 31 | Total Accepted:162.1K 32 | Total Submissions:348.7K 33 | 34 | 35 | Companies Adobe Apple Microsoft 36 | Related Topics Linked List 37 | Similar Questions 38 | 39 | 40 | Remove Linked List Elements 41 | */ 42 | -------------------------------------------------------------------------------- /238. Product of Array Except Self.c: -------------------------------------------------------------------------------- 1 | /* 2 | 238. Product of Array Except Self 3 | 4 | Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 5 | 6 | Solve it without division and in O(n). 7 | 8 | For example, given [1,2,3,4], return [24,12,8,6]. 9 | 10 | Follow up: 11 | Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.) 12 | */ 13 | 14 | /** 15 | * Return an array of size *returnSize. 16 | * Note: The returned array must be malloced, assume caller calls free(). 17 | */ 18 | int* productExceptSelf(int* nums, int numsSize, int* returnSize) { 19 |    int *x = malloc(numsSize * sizeof(int)); 20 |    //assert(x); 21 |    int i, j, k; 22 |     23 |    x[0] = 1; 24 |    for (i = 1; i < numsSize; i ++) { 25 |        x[i] = x[i - 1] * nums[i - 1]; 26 |   } 27 |    k = nums[numsSize - 1]; 28 |    for (i = numsSize - 2; i >= 0; i --) { 29 |        x[i] = x[i] * k; 30 |        k *= nums[i]; 31 |   } 32 |     33 |    *returnSize = numsSize; 34 |    return x; 35 | } 36 | 37 | 38 | /* 39 | Difficulty:Medium 40 | Total Accepted:106.1K 41 | Total Submissions:216.4K 42 | 43 | 44 | Companies Amazon LinkedIn Apple Facebook Microsoft 45 | Related Topics Array 46 | Similar Questions 47 | 48 | 49 | Trapping Rain Water 50 | 51 | Maximum Product Subarray 52 | 53 | Paint House II 54 | */ 55 | -------------------------------------------------------------------------------- /24. Swap Nodes in Pairs.c: -------------------------------------------------------------------------------- 1 | /* 2 | 24. Swap Nodes in Pairs 3 | 4 | Given a linked list, swap every two adjacent nodes and return its head. 5 | 6 | 7 | 8 | For example, 9 | Given 1->2->3->4, you should return the list as 2->1->4->3. 10 | 11 | 12 | 13 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 14 | */ 15 | 16 | /** 17 | * Definition for singly-linked list. 18 | * struct ListNode { 19 | * int val; 20 | * struct ListNode *next; 21 | * }; 22 | */ 23 | struct ListNode* swapPairs(struct ListNode* head) { 24 | struct ListNode *a, *b, *c; 25 | 26 | a = head; 27 | if (a && a->next) { 28 | b = a->next; 29 | c = b->next; 30 | b->next = a; 31 | a->next = swapPairs(c); 32 | return b; 33 | } 34 | 35 | return a; 36 | } 37 | 38 | /* 39 | Difficulty:Medium 40 | Total Accepted:181.1K 41 | Total Submissions:470K 42 | 43 | 44 | Companies Microsoft Bloomberg Uber 45 | Related Topics Linked List 46 | Similar Questions 47 | 48 | 49 | Reverse Nodes in k-Group 50 | */ 51 | -------------------------------------------------------------------------------- /242. Valid Anagram.c: -------------------------------------------------------------------------------- 1 | /* 2 | 242. Valid Anagram 3 | 4 | Given two strings s and t, write a function to determine if t is an anagram of s. 5 | 6 | For example, 7 | s = "anagram", t = "nagaram", return true. 8 | s = "rat", t = "car", return false. 9 | 10 | 11 | Note: 12 | You may assume the string contains only lowercase alphabets. 13 | 14 | Follow up: 15 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 16 | */ 17 | 18 | bool isAnagram(char* s, char* t) { 19 |    int n1[26] = { 0 }, n2[26] = { 0 }; 20 |    int i, j; 21 |     22 |    while (*s && *t) { 23 |        i = *s - 'a'; 24 |        j = *t - 'a'; 25 |        n1[i] ++; 26 |        n2[j] ++; 27 |        s ++; 28 |        t ++; 29 |   } 30 |     31 |    if (*s || *t) return false; 32 |     33 |    for (i = 0; i < 26; i ++) { 34 |        if (n1[i] != n2[i]) return false; 35 |   } 36 |     37 |    return true; 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Easy 43 | Total Accepted:165.9K 44 | Total Submissions:357.7K 45 | 46 | 47 | Companies Amazon Uber Yelp 48 | Related Topics Hash Table Sort 49 | Similar Questions 50 | 51 | 52 | Group Anagrams 53 | 54 | Palindrome Permutation 55 | 56 | Find All Anagrams in a String 57 | */ 58 | -------------------------------------------------------------------------------- /246. Strobogrammatic Number.c: -------------------------------------------------------------------------------- 1 | /* 2 | 246. Strobogrammatic Number 3 | 4 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 5 | Write a function to determine if a number is strobogrammatic. The number is represented as a string. 6 | For example, the numbers "69", "88", and "818" are all strobogrammatic. 7 | */ 8 | 9 | bool isStrobogrammatic(char* num) { 10 |    int m[10] = { 0, 1, -1, -1, -1, -1, 9, -1, 8, 6 }; 11 |    int i, j, a, b; 12 |    int l = strlen(num); 13 | ​ 14 |    for (i = 0, j = l - 1; i <= j; i ++, j --) { 15 |        a = num[i] - '0'; 16 |        b = num[j] - '0'; 17 |        //printf("%d ... %d\n", a, b); 18 |        if (m[a] != b) { 19 |            return false; 20 |       } 21 |   } 22 | ​ 23 |    return true; 24 | } 25 | 26 | 27 | /* 28 | Difficulty:Easy 29 | Total Accepted:27.3K 30 | Total Submissions:68.6K 31 | 32 | 33 | Companies Google 34 | Related Topics Hash Table Math 35 | Similar Questions 36 | 37 | 38 | Strobogrammatic Number II 39 | 40 | Strobogrammatic Number III 41 | */ 42 | -------------------------------------------------------------------------------- /259. 3Sum Smaller.c: -------------------------------------------------------------------------------- 1 | /* 2 | 259. 3Sum Smaller 3 | 4 | Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target. 5 | 6 | For example, given nums = [-2, 0, 1, 3], and target = 2. 7 | 8 | Return 2. Because there are two triplets which sums are less than 2: 9 | [-2, 0, 1] 10 | [-2, 0, 3] 11 | 12 | 13 | Follow up: 14 | Could you solve it in O(n2) runtime? 15 | */ 16 | 17 | int cmp(void *a, void *b) { 18 |    return *(int *)a - *(int *)b; 19 | } 20 | int threeSumSmaller(int* nums, int numsSize, int target) { 21 |    int i, x, y, k; 22 |    int n = 0; 23 |    qsort(nums, numsSize, sizeof(int), cmp); 24 |    for (i = 0; i < numsSize - 2; i ++) { 25 |        x = i + 1; 26 |        y = numsSize - 1; 27 |        while (x < y) { 28 |            if (nums[i] + nums[x] + nums[y] >= target) { 29 |                y --; 30 |           } else { 31 |                n += y - x; 32 |                x ++; 33 |           } 34 |       } 35 |   } 36 |    return n; 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Medium 42 | Total Accepted:26.6K 43 | Total Submissions:64.5K 44 | 45 | 46 | Companies Google 47 | Related Topics Array Two Pointers 48 | Similar Questions 49 | 50 | 51 | 3Sum 52 | 53 | 3Sum Closest 54 | 55 | Valid Triangle Number 56 | */ 57 | -------------------------------------------------------------------------------- /26. Remove Duplicates from Sorted Array.c: -------------------------------------------------------------------------------- 1 | /* 2 | 26. Remove Duplicates from Sorted Array 3 | 4 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 5 | 6 | 7 | Do not allocate extra space for another array, you must do this in place with constant memory. 8 | 9 | 10 | 11 | For example, 12 | Given input array nums = [1,1,2], 13 | 14 | 15 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 16 | */ 17 | 18 | int removeDuplicates(int* nums, int numsSize) { 19 |    int i, j; 20 |     21 |    if (numsSize < 2) return numsSize; 22 |     23 |    for (i = 0, j = 1; j < numsSize; j ++) { 24 |        if (nums[j] != nums[i]) { 25 |            i ++; 26 |            nums[i] = nums[j]; 27 |       } 28 |   } 29 |     30 |    return i + 1; 31 | } 32 | 33 | 34 | /* 35 | Difficulty:Easy 36 | Total Accepted:249.5K 37 | Total Submissions:703.3K 38 | 39 | 40 | Companies Microsoft Bloomberg Facebook 41 | Related Topics Array Two Pointers 42 | Similar Questions 43 | 44 | 45 | Remove Element 46 | */ 47 | -------------------------------------------------------------------------------- /260. Single Number III.c: -------------------------------------------------------------------------------- 1 | /* 2 | 260. Single Number III 3 | 4 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 5 | 6 | 7 | For example: 8 | 9 | 10 | Given nums = [1, 2, 1, 3, 2, 5], return [3, 5]. 11 | 12 | 13 | Note: 14 | 15 | The order of the result is not important. So in the above example, [5, 3] is also correct. 16 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 17 | 18 | 19 | 20 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 21 | */ 22 | 23 | /** 24 | * Return an array of size *returnSize. 25 | * Note: The returned array must be malloced, assume caller calls free(). 26 | */ 27 | int* singleNumber(int* nums, int numsSize, int* returnSize) { 28 |    int i, k, a, b, *p; 29 |     30 |    k = 0; 31 |    for (i = 0; i < numsSize; i ++) { 32 |        k ^= nums[i]; 33 |   } 34 |     35 |    k = k & ~(k - 1); 36 |    a = b = 0; 37 |    for (i = 0; i < numsSize; i ++) { 38 |        if (nums[i] & k) { 39 |            a ^= nums[i]; 40 |       } else { 41 |            b ^= nums[i]; 42 |       } 43 |   } 44 |     45 |    p = malloc(2 * sizeof(int)); 46 |    p[0] = a; 47 |    p[1] = b; 48 |    *returnSize = 2; 49 |    return p; 50 | } 51 | 52 | 53 | /* 54 | Difficulty:Medium 55 | Total Accepted:69.2K 56 | Total Submissions:134.3K 57 | 58 | 59 | Related Topics Bit Manipulation 60 | Similar Questions Single Number Single Number II 61 | 62 | */ 63 | -------------------------------------------------------------------------------- /261. Graph Valid Tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | 261. Graph Valid Tree 3 | 4 | Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. 5 | 6 | 7 | 8 | For example: 9 | 10 | 11 | Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true. 12 | 13 | 14 | Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false. 15 | 16 | 17 | 18 | Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. 19 | */ 20 | 21 | bool validTree(int n, int** edges, int edgesRowSize, int edgesColSize) { 22 |    int *p, i, a, b, root = 0; 23 |     24 |    p = calloc(n, sizeof(int)); 25 |    //assert(p); 26 |     27 |    for (i = 0; i < edgesRowSize; i ++) { 28 |        a = edges[i][0]; 29 |        b = edges[i][1]; 30 |        while (p[a]) a = p[a] - 1;  // go all way up to the top parent 31 |        while (p[b]) b = p[b] - 1; 32 |        if (a == b) goto done;  // if they have same parent, this forms a loop 33 |        p[a] = b + 1;  // set the parent 34 |   } 35 |     36 |    free(p); 37 |    return edgesRowSize == n - 1 ? true : false;  // n nodes require n - 1 edges to form a tree 38 | done: 39 |    free(p); 40 |    return false; 41 | } 42 | 43 | 44 | /* 45 | Difficulty:Medium 46 | Total Accepted:38.6K 47 | Total Submissions:102.4K 48 | 49 | 50 | Companies Google Facebook Zenefits 51 | Related Topics Depth-first Search Breadth-first Search Graph Union Find 52 | Similar Questions 53 | 54 | 55 | Course Schedule 56 | 57 | Number of Connected Components in an Undirected Graph 58 | */ 59 | -------------------------------------------------------------------------------- /263. Ugly Number.c: -------------------------------------------------------------------------------- 1 | /* 2 | 263. Ugly Number 3 | 4 | Write a program to check whether a given number is an ugly number. 5 | 6 | 7 | 8 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 9 | 10 | 11 | 12 | Note that 1 is typically treated as an ugly number. 13 | 14 | 15 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 16 | */ 17 | 18 | bool isUgly(int num) { 19 |    int pf[] = { 2, 3, 5 }; 20 |    int i = sizeof(pf) / sizeof(pf[0]); 21 |    while (num && -- i >= 0) { 22 |        while (!(num % pf[i])) { 23 |            num = num / pf[i]; 24 |            //printf("%d, ", num); 25 |       } 26 |   } 27 |    return num == 1 ? true : false; 28 | } 29 | 30 | 31 | /* 32 | Difficulty:Easy 33 | Total Accepted:104.7K 34 | Total Submissions:267K 35 | 36 | 37 | Related Topics Math 38 | Similar Questions Happy Number Count Primes Ugly Number II 39 | 40 | */ 41 | -------------------------------------------------------------------------------- /264. Ugly Number II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 264. Ugly Number II 3 | 4 | Write a program to find the n-th ugly number. 5 | 6 | 7 | 8 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 9 | 10 | 11 | 12 | Note that 1 is typically treated as an ugly number, and n does not exceed 1690. 13 | 14 | 15 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 16 | */ 17 | 18 | int nthUglyNumber(int n) { 19 |    int i, u2, u3, u5, k2, k3, k5, k; 20 |    int *p, sz; 21 |     22 |    p  = malloc(n * sizeof(int)); 23 |    //assert(p); 24 |     25 |    p[0] = 1; 26 |    u2 = u3 = u5 = 0; 27 |     28 |    for (i = 1; i < n; i ++) {  // more like dp solution, 3ms 29 |        k2 = p[u2] * 2; 30 |        k3 = p[u3] * 3; 31 |        k5 = p[u5] * 5; 32 |        k = k2 < k3 ? k2 : k3; 33 |        k = k  < k5 ? k : k5; 34 |        if (k == k2) u2 ++; 35 |        if (k == k3) u3 ++; 36 |        if (k == k5) u5 ++; 37 |        p[i] = k; 38 |   } 39 |     40 |    k = p[n - 1]; 41 |    free(p); 42 |     43 |    return k; 44 | } 45 | 46 | 47 | /* 48 | Difficulty:Medium 49 | Total Accepted:61K 50 | Total Submissions:187.2K 51 | 52 | 53 | Related Topics Dynamic Programming Heap Math 54 | Similar Questions Merge k Sorted Lists Count Primes Ugly Number Perfect Squares Super Ugly Number 55 | 56 | */ 57 | -------------------------------------------------------------------------------- /265. Paint House II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 265. Paint House II 3 | 4 | There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. 5 | 6 | 7 | The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses. 8 | 9 | 10 | Note: 11 | All costs are positive integers. 12 | 13 | Follow up: 14 | Could you solve it in O(nk) runtime? 15 | */ 16 | 17 | void dfs(int *m, int cost, int r, int p, int **costs, int rowsz, int colsz) { 18 |    int k; 19 |     20 |    if (*m && *m < cost) return; 21 |     22 |    if (r == rowsz) { 23 |        if (*m == 0 || *m > cost) *m = cost; 24 |   } else { 25 |        for (k = 0; k < colsz; k ++) { 26 |            if (k != p) { 27 |                dfs(m, cost + costs[r][k], r + 1, k, costs, rowsz, colsz); 28 |           } 29 |       } 30 |   } 31 | } 32 | int minCostII(int** costs, int costsRowSize, int costsColSize) { 33 |    int m = 0; 34 |     35 |    dfs(&m, 0, 0, -1, costs, costsRowSize, costsColSize); 36 |     37 |    return m; 38 | } 39 | ​ 40 | // use dp solution, refer to Paint House I 41 | 42 | 43 | /* 44 | Difficulty:Hard 45 | Total Accepted:22.3K 46 | Total Submissions:58.6K 47 | 48 | 49 | Companies Facebook 50 | Related Topics Dynamic Programming 51 | Similar Questions 52 | 53 | 54 | Product of Array Except Self 55 | 56 | Sliding Window Maximum 57 | 58 | Paint House 59 | 60 | Paint Fence 61 | */ 62 | -------------------------------------------------------------------------------- /266. Palindrome Permutation.c: -------------------------------------------------------------------------------- 1 | /* 2 | 266. Palindrome Permutation 3 | 4 | Given a string, determine if a permutation of the string could form a palindrome. 5 | 6 | For example, 7 | "code" -> False, "aab" -> True, "carerac" -> True. 8 | */ 9 | 10 | bool canPermutePalindrome(char* s) { 11 |    int i, odd; 12 |    int n[128] = { 0 }; 13 |    while (*s) n[*(s ++)] ++; 14 |    odd = 0; 15 |    for (i = 0; i < 128; i ++) { 16 |        if (n[i] % 2) { 17 |            if (odd) return false; 18 |            odd = 1; 19 |       } 20 |   } 21 |    return true; 22 | } 23 | 24 | 25 | /* 26 | Difficulty:Easy 27 | Total Accepted:33.2K 28 | Total Submissions:58.4K 29 | 30 | 31 | Companies Google Uber Bloomberg 32 | Related Topics Hash Table 33 | Similar Questions 34 | 35 | 36 | Longest Palindromic Substring 37 | 38 | Valid Anagram 39 | 40 | Palindrome Permutation II 41 | 42 | Longest Palindrome 43 | */ 44 | -------------------------------------------------------------------------------- /268. Missing Number.c: -------------------------------------------------------------------------------- 1 | /* 2 | 268. Missing Number 3 | 4 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 5 | 6 | 7 | For example, 8 | Given nums = [0, 1, 3] return 2. 9 | 10 | 11 | 12 | Note: 13 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 14 | 15 | 16 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 17 | */ 18 | 19 | int missingNumber(int* nums, int numsSize) { 20 |    int i, k; 21 | #if 0 22 |    k = numsSize; 23 |    for (i = 0; i < numsSize; i ++) { 24 |        k = k ^ i ^ nums[i]; 25 |   } 26 | #else 27 |    k = numsSize * (numsSize + 1) / 2; 28 |    for (i = 0; i < numsSize; i ++) { 29 |        k -= nums[i]; 30 |   } 31 | #endif 32 |    return k; 33 | } 34 | 35 | 36 | /* 37 | Difficulty:Easy 38 | Total Accepted:125.4K 39 | Total Submissions:283.6K 40 | 41 | 42 | Companies Microsoft Bloomberg 43 | Related Topics Array Math Bit Manipulation 44 | Similar Questions 45 | 46 | 47 | First Missing Positive 48 | 49 | Single Number 50 | 51 | Find the Duplicate Number 52 | */ 53 | -------------------------------------------------------------------------------- /270. Closest Binary Search Tree Value.c: -------------------------------------------------------------------------------- 1 | /* 2 | 270. Closest Binary Search Tree Value 3 | 4 | Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. 5 | 6 | Note: 7 | 8 | Given target value is a floating point. 9 | You are guaranteed to have only one unique value in the BST that is closest to the target. 10 | */ 11 | 12 | /** 13 | * Definition for a binary tree node. 14 | * struct TreeNode { 15 | *     int val; 16 | *     struct TreeNode *left; 17 | *     struct TreeNode *right; 18 | * }; 19 | */ 20 | void search(struct TreeNode *node, double target, int *last) { 21 |    double d, diff1, diff2; 22 |     23 |    if (!node) return; 24 |     25 |    d = node->val;  // current one 26 |    diff1 = target - (*last); 27 |    diff2 = target - d; 28 |     29 |    if (diff1 < 0) diff1 = 0 - diff1; 30 |    if (diff2 < 0) diff2 = 0 - diff2; 31 |    if (diff1 > diff2) *last = d;       // closest one so far 32 |     33 |    if (target < d) { 34 |        search(node->left, target, last); 35 |   } else 36 |    if (target > d) { 37 |        search(node->right, target, last); 38 |   } 39 | } 40 | int closestValue(struct TreeNode* root, double target) { 41 |    int last = root->val; 42 |    search(root, target, &last); 43 |    return last; 44 | } 45 | 46 | 47 | /* 48 | Difficulty:Easy 49 | Total Accepted:36.3K 50 | Total Submissions:92.2K 51 | 52 | 53 | Companies Microsoft Google Snapchat 54 | Related Topics Tree Binary Search 55 | Similar Questions 56 | 57 | 58 | Count Complete Tree Nodes 59 | 60 | Closest Binary Search Tree Value II 61 | */ 62 | -------------------------------------------------------------------------------- /275. H-Index II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 275. H-Index II 3 | 4 | Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm? 5 | */ 6 | 7 | int hIndex(int* citations, int citationsSize) { 8 |    int i, h = 0; 9 |    for (i = 0; i < citationsSize; i ++) { 10 |        if (citations[citationsSize - 1 - i] >= i + 1) { 11 |            h = i + 1; 12 |       } else { 13 |            break; 14 |       } 15 |   } 16 |    return h; 17 | } 18 | 19 | 20 | /* 21 | Difficulty:Medium 22 | Total Accepted:50.2K 23 | Total Submissions:146.3K 24 | 25 | 26 | Companies Facebook 27 | Related Topics Binary Search 28 | Similar Questions 29 | 30 | 31 | H-Index 32 | */ 33 | -------------------------------------------------------------------------------- /276. Paint Fence.c: -------------------------------------------------------------------------------- 1 | /* 2 | 276. Paint Fence 3 | 4 | There is a fence with n posts, each post can be painted with one of the k colors. 5 | You have to paint all the posts such that no more than two adjacent fence posts have the same color. 6 | Return the total number of ways you can paint the fence. 7 | 8 | Note: 9 | n and k are non-negative integers. 10 | */ 11 | 12 | int numWays(int n, int k) { 13 |    int total; 14 |    int i; 15 | ​ 16 |    int same = 0; 17 |    int diff = k; 18 |    if (!n) return 0; 19 |    for (i = 1; i < n; i ++) { 20 |        total = same + diff; 21 |        same = diff; 22 |        diff = total * (k - 1); 23 |   } 24 |    total = same + diff; 25 | ​ 26 |    return total; 27 | } 28 | ​ 29 | // no more than three adjacent posts having the same color 30 | // most straightforward approach is dfs, this is dp solution 31 | ​ 32 | /* 33 | if (!n) return 0; 34 | if (n == 1) return k; 35 | s3 = 0; // all three the same 36 | s2 = k; // the last two the same 37 | diff = k * (k - 1); 38 | for (i = 2; i < n; i ++) { 39 |    total = s2 + s3 + diff; 40 |    s3 = s2 41 |    s2 = diff 42 |    diff = total * (k - 1); 43 | } 44 | */ 45 | 46 | 47 | /* 48 | Difficulty:Easy 49 | Total Accepted:24.2K 50 | Total Submissions:70.6K 51 | 52 | 53 | Companies Google 54 | Related Topics Dynamic Programming 55 | Similar Questions 56 | 57 | 58 | House Robber 59 | 60 | House Robber II 61 | 62 | Paint House 63 | 64 | Paint House II 65 | */ 66 | -------------------------------------------------------------------------------- /277. Find the Celebrity.c: -------------------------------------------------------------------------------- 1 | /* 2 | 277. Find the Celebrity 3 | 4 | Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. 5 | 6 | 7 | 8 | Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). 9 | 10 | 11 | 12 | You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows. 13 | 14 | 15 | 16 | Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. 17 | */ 18 | 19 | // Forward declaration of the knows API. 20 | bool knows(int a, int b); 21 | ​ 22 | int findCelebrity(int n) { 23 |    int candidate = 0; 24 |    int i; 25 |     26 |    // find the candidate 27 |    for (i = 1; i < n; i ++) { 28 |        if (knows(candidate, i)) candidate = i; 29 |   } 30 |     31 |    for (i = 0; i < n; i ++) { 32 |        if (i != candidate && 33 |           (!knows(i, candidate) || knows(candidate, i))) return -1; 34 |   } 35 |     36 |    return candidate; 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Medium 42 | Total Accepted:31.5K 43 | Total Submissions:89.1K 44 | 45 | 46 | Companies LinkedIn Facebook 47 | Related Topics Array 48 | 49 | */ 50 | -------------------------------------------------------------------------------- /278. First Bad Version.c: -------------------------------------------------------------------------------- 1 | /* 2 | 278. First Bad Version 3 | 4 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 5 | 6 | 7 | 8 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 9 | 10 | 11 | 12 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 13 | 14 | 15 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 16 | */ 17 | 18 | // Forward declaration of isBadVersion API. 19 | bool isBadVersion(int version); 20 | ​ 21 | int firstBadVersion(int n) { 22 |    int left, right, mid; 23 |    left = 1; right = n; 24 |    while (left < right) { 25 |        mid = left + (right - left) / 2; 26 |        if (isBadVersion(mid)) { 27 |            right = mid; 28 |       } else { 29 |            left = mid + 1; 30 |       } 31 |   } 32 |    return right; 33 | } 34 | 35 | 36 | /* 37 | Difficulty:Easy 38 | Total Accepted:107.3K 39 | Total Submissions:424.8K 40 | 41 | 42 | Companies Facebook 43 | Related Topics Binary Search 44 | Similar Questions 45 | 46 | 47 | Search for a Range 48 | 49 | Search Insert Position 50 | 51 | Guess Number Higher or Lower 52 | */ 53 | -------------------------------------------------------------------------------- /279. Perfect Squares.c: -------------------------------------------------------------------------------- 1 | /* 2 | 279. Perfect Squares 3 | 4 | Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 5 | 6 | 7 | 8 | For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. 9 | 10 | 11 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 12 | */ 13 | 14 | int numSquares(int n) { 15 | int i, j, k; 16 | int *dp; 17 | 18 | dp = malloc((n + 1) * sizeof(int)); 19 | //assert(dp); 20 | 21 | dp[0] = 0; 22 | for (i = 1; i <= n; i ++) { 23 | k = dp[i - 1] + 1; // answer of preceeding number plus 1 24 | j = 2; 25 | while (i >= j * j) { // after j ^ 2 26 | if (k > dp[i - j * j] + 1) { 27 | k = dp[i - j * j] + 1; 28 | } 29 | j ++; 30 | } 31 | dp[i] = k; 32 | } 33 | 34 | k = dp[n]; 35 | free(dp); 36 | 37 | return k; 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Medium 43 | Total Accepted:81.3K 44 | Total Submissions:220.9K 45 | 46 | 47 | Companies Google 48 | Related Topics Dynamic Programming Breadth-first Search Math 49 | Similar Questions 50 | 51 | 52 | Count Primes 53 | 54 | Ugly Number II 55 | */ 56 | -------------------------------------------------------------------------------- /28. Implement strStr().c: -------------------------------------------------------------------------------- 1 | /* 2 | 28. Implement strStr() 3 | 4 | Implement strStr(). 5 | 6 | 7 | Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 8 | */ 9 | 10 | int strStr(char* haystack, char* needle) { 11 |    int i, j, l1, l2; 12 |     13 |    if (!haystack || !needle) return -1; 14 |     15 |    l2 = strlen(needle); 16 |    if (!l2) return 0; 17 |     18 |    l1 = strlen(haystack); 19 |     20 |    for (i = 0; i <= l1 - l2; i ++) { 21 |        for (j = 0; j < l2 && haystack[i + j] == needle[j]; j ++) { 22 |       } 23 |        if (j == l2) return i; 24 |   } 25 |     26 |    return -1; 27 | } 28 | 29 | 30 | /* 31 | Difficulty:Easy 32 | Total Accepted:197.8K 33 | Total Submissions:703.9K 34 | 35 | 36 | Companies Pocket Gems Microsoft Apple Facebook 37 | Related Topics Two Pointers String 38 | Similar Questions 39 | 40 | 41 | Shortest Palindrome 42 | 43 | Repeated Substring Pattern 44 | */ 45 | -------------------------------------------------------------------------------- /280. Wiggle Sort.c: -------------------------------------------------------------------------------- 1 | /* 2 | 280. Wiggle Sort 3 | 4 | Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 5 | 6 | 7 | For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 8 | */ 9 | 10 | int qf(void *a, void *b) { 11 |    return *(int *)a - *(int *)b; 12 | } 13 | void wiggleSort(int* nums, int numsSize) { 14 |    int i, j, k; 15 | #if 0 16 |    qsort(nums, numsSize, sizeof(int), qf); 17 |    for (i = 1; i < numsSize - 1; i += 2) { 18 |        k = nums[numsSize - 1]; 19 |        for (j = numsSize - 1; j > i; j --) { 20 |            nums[j] = nums[j - 1]; 21 |       } 22 |        nums[i] = k; 23 |   } 24 | #else 25 |    for (i = 1; i < numsSize; i ++) { 26 |        if (!((i % 2) ^ (nums[i - 1] > nums[i]))/* || 27 |            (!(i % 2) && (nums[i - 1] < nums[i]))*/) { 28 |            k = nums[i - 1]; 29 |            nums[i - 1] = nums[i];  // swap 30 |            nums[i] = k; 31 |       } 32 |   } 33 | #endif 34 | } 35 | 36 | 37 | /* 38 | Difficulty:Medium 39 | Total Accepted:29.9K 40 | Total Submissions:52.5K 41 | 42 | 43 | Companies Google 44 | Related Topics Array Sort 45 | Similar Questions 46 | 47 | 48 | Sort Colors 49 | 50 | Wiggle Sort II 51 | */ 52 | -------------------------------------------------------------------------------- /283. Move Zeroes.c: -------------------------------------------------------------------------------- 1 | /* 2 | 283. Move Zeroes 3 | 4 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 5 | 6 | 7 | 8 | For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. 9 | 10 | 11 | 12 | Note: 13 | 14 | You must do this in-place without making a copy of the array. 15 | Minimize the total number of operations. 16 | 17 | 18 | 19 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 20 | */ 21 | 22 | void moveZeroes(int* nums, int numsSize) { 23 |    int i, j, k; 24 |    for (i = 0, j = 0; j < numsSize; j ++) { 25 |        if (nums[j] != 0) { 26 |            nums[i ++] = nums[j]; 27 |       } 28 |   } 29 |    memset(&nums[i], 0, (j - i) * sizeof(int)); 30 | } 31 | 32 | 33 | /* 34 | Difficulty:Easy 35 | Total Accepted:202.9K 36 | Total Submissions:407K 37 | 38 | 39 | Companies Bloomberg Facebook 40 | Related Topics Array Two Pointers 41 | Similar Questions 42 | 43 | 44 | Remove Element 45 | */ 46 | -------------------------------------------------------------------------------- /285. Inorder Successor in BST.c: -------------------------------------------------------------------------------- 1 | /* 2 | 285. Inorder Successor in BST 3 | 4 | Given a binary search tree and a node in it, find the in-order successor of that node in the BST. 5 | 6 | 7 | 8 | Note: If the given node has no in-order successor in the tree, return null. 9 | */ 10 | 11 | /** 12 | * Definition for a binary tree node. 13 | * struct TreeNode { 14 | *     int val; 15 | *     struct TreeNode *left; 16 | *     struct TreeNode *right; 17 | * }; 18 | */ 19 | struct TreeNode* inorderSuccessor(struct TreeNode* root, struct TreeNode* p) { 20 |    struct TreeNode *succ = NULL; 21 |    //if (!root) return NULL; 22 |    //if (root->val <= p->val) return inorderSuccessor(root->right, p); 23 |    //succ = inorderSuccessor(root->left, p); 24 |    //return succ ? succ : root; 25 |    while (root) { 26 |        if (root->val <= p->val) { // go to right 27 |            root = root->right; 28 |       } else { 29 |            succ = root; 30 |            root = root->left; 31 |       } 32 |   } 33 |    return succ; 34 | } 35 | 36 | 37 | /* 38 | Difficulty:Medium 39 | Total Accepted:36.4K 40 | Total Submissions:101.1K 41 | 42 | 43 | Companies Pocket Gems Microsoft Facebook 44 | Related Topics Tree 45 | Similar Questions 46 | 47 | 48 | Binary Tree Inorder Traversal 49 | 50 | Binary Search Tree Iterator 51 | */ 52 | -------------------------------------------------------------------------------- /287. Find the Duplicate Number.c: -------------------------------------------------------------------------------- 1 | /* 2 | 287. Find the Duplicate Number 3 | 4 | Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 5 | 6 | 7 | 8 | Note: 9 | 10 | You must not modify the array (assume the array is read only). 11 | You must use only constant, O(1) extra space. 12 | Your runtime complexity should be less than O(n2). 13 | There is only one duplicate number in the array, but it could be repeated more than once. 14 | 15 | 16 | 17 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 18 | */ 19 | 20 | int findDuplicate(int* nums, int numsSize) { 21 |    int slow, fast; 22 |     23 |    slow = fast = 0; 24 |    do { 25 |        slow = nums[slow];          // one step 26 |        fast = nums[nums[fast]];    // two steps 27 |   } while (slow != fast); 28 |     29 |    slow = 0; 30 |    do { 31 |        slow = nums[slow]; 32 |        fast = nums[fast]; 33 |   } while (slow != fast); // start of the cycle 34 |     35 |    return slow; 36 | } 37 | 38 | 39 | /* 40 | Difficulty:Medium 41 | Total Accepted:75.7K 42 | Total Submissions:174.4K 43 | 44 | 45 | Companies Bloomberg 46 | Related Topics Binary Search Array Two Pointers 47 | Similar Questions 48 | 49 | 50 | First Missing Positive 51 | 52 | Single Number 53 | 54 | Linked List Cycle II 55 | 56 | Missing Number 57 | 58 | Set Mismatch 59 | */ 60 | -------------------------------------------------------------------------------- /292. Nim Game.c: -------------------------------------------------------------------------------- 1 | /* 2 | 292. Nim Game 3 | 4 | You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 5 | 6 | 7 | 8 | Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 9 | 10 | 11 | 12 | For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. 13 | 14 | 15 | Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 16 | */ 17 | 18 | bool canWinNim(int n) { 19 | #if 0 20 |    int i, hewins; 21 |     22 |    if (n <= 3) return true; 23 |    for (i = 1; i <= 3; i ++) { 24 |        hewins = canWinNim(n - i); 25 |        if (!hewins) return true; 26 |   } 27 |     28 |    return false; 29 | #else 30 |    return (n % 4) ? true : false; 31 | #endif 32 | } 33 | 34 | 35 | /* 36 | Difficulty:Easy 37 | Total Accepted:140.1K 38 | Total Submissions:253.7K 39 | 40 | 41 | Companies Adobe 42 | Related Topics Brainteaser 43 | Similar Questions 44 | 45 | 46 | Flip Game II 47 | */ 48 | -------------------------------------------------------------------------------- /294. Flip Game II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 294. Flip Game II 3 | 4 | You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner. 5 | 6 | 7 | 8 | Write a function to determine if the starting player can guarantee a win. 9 | 10 | 11 | 12 | For example, given s = "++++", return true. The starting player can guarantee a win by flipping the middle "++" to become "+--+". 13 | 14 | 15 | Follow up: 16 | Derive your algorithm's runtime complexity. 17 | */ 18 | 19 | bool canWin(char* s) { 20 |    bool hewins; 21 |    char *p = s; 22 |    while (*p && *(p + 1)) { 23 |        if (*p == '+' && *(p + 1) == '+') { 24 |            *p = *(p + 1) = '-'; 25 |            hewins = canWin(s); 26 |            *p = *(p + 1) = '+'; 27 |            if (!hewins) return true; 28 |       } 29 |        p ++; 30 |   } 31 |    return false; 32 | } 33 | 34 | 35 | /* 36 | Difficulty:Medium 37 | Total Accepted:26.1K 38 | Total Submissions:56.5K 39 | 40 | 41 | Companies Google 42 | Related Topics Backtracking 43 | Similar Questions 44 | 45 | 46 | Nim Game 47 | 48 | Flip Game 49 | 50 | Guess Number Higher or Lower II 51 | 52 | Can I Win 53 | */ 54 | -------------------------------------------------------------------------------- /3. Longest Substring Without Repeating Characters.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3. Longest Substring Without Repeating Characters 3 | 4 | Given a string, find the length of the longest substring without repeating characters. 5 | 6 | Examples: 7 | 8 | Given "abcabcbb", the answer is "abc", which the length is 3. 9 | 10 | Given "bbbbb", the answer is "b", with the length of 1. 11 | 12 | Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 13 | */ 14 | 15 | int lengthOfLongestSubstring(char* s) { 16 |    int i, j, l, k = 0; 17 |    char c; 18 |    int pos[128] = { 0 }; 19 |    char *p; 20 |    int n = 0; 21 |     22 |    for (i = 0; s[i]; i ++) { 23 |        n ++; 24 |        c = s[i]; 25 |        l = i - pos[c] + 1; 26 |        pos[c] = i + 1; 27 |        n = n < l ? n : l; 28 |        k = k > n ? k : n; 29 |   } 30 |     31 |    return k; 32 | } 33 | 34 | 35 | /* 36 | Difficulty:Medium 37 | Total Accepted:330.3K 38 | Total Submissions:1.4M 39 | 40 | 41 | Companies Amazon Adobe Bloomberg Yelp 42 | Related Topics Hash Table Two Pointers String 43 | Similar Questions 44 | 45 | 46 | Longest Substring with At Most Two Distinct Characters 47 | */ 48 | -------------------------------------------------------------------------------- /31. Next Permutation.c: -------------------------------------------------------------------------------- 1 | /* 2 | 31. Next Permutation 3 | 4 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 5 | 6 | 7 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 8 | 9 | 10 | The replacement must be in-place, do not allocate extra memory. 11 | 12 | 13 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 14 | 1,2,3 → 1,3,2 15 | 3,2,1 → 1,2,3 16 | 1,1,5 → 1,5,1 17 | */ 18 | 19 | int cmp(const void *a, const void *b) { 20 |    return *(int *)a - *(int *)b; 21 | } 22 | void nextPermutation(int* nums, int numsSize) { 23 |    int i, j, k; 24 |    for (i = numsSize - 1; i > 0; i --) { 25 |        if (nums[i - 1] < nums[i]) { 26 |            j = i - 1;  // this is the first small number from tail 27 |            while (i < numsSize - 1 && 28 |                nums[i + 1] > nums[j]) {  // find the second small number in the tail 29 |                i ++; 30 |           } 31 |            k = nums[i];  // swap it 32 |            nums[i] = nums[j]; 33 |            nums[j] = k; 34 |            qsort(&nums[j + 1], numsSize - j - 1, sizeof(int), cmp); 35 |            return; 36 |       } 37 |   } 38 |    qsort(nums, numsSize, sizeof(int), cmp); 39 | } 40 | 41 | 42 | /* 43 | Difficulty:Medium 44 | Total Accepted:116.6K 45 | Total Submissions:405.2K 46 | 47 | 48 | Companies Google 49 | Related Topics Array 50 | Similar Questions 51 | 52 | 53 | Permutations 54 | 55 | Permutations II 56 | 57 | Permutation Sequence 58 | 59 | Palindrome Permutation II 60 | */ 61 | -------------------------------------------------------------------------------- /311. Sparse Matrix Multiplication.c: -------------------------------------------------------------------------------- 1 | /* 2 | 311. Sparse Matrix Multiplication 3 | 4 | Given two sparse matrices A and B, return the result of AB. 5 | 6 | You may assume that A's column number is equal to B's row number. 7 | 8 | Example: 9 | 10 | A = [ 11 | [ 1, 0, 0], 12 | [-1, 0, 3] 13 | ] 14 | 15 | B = [ 16 | [ 7, 0, 0 ], 17 | [ 0, 0, 0 ], 18 | [ 0, 0, 1 ] 19 | ] 20 | 21 | 22 | | 1 0 0 | | 7 0 0 | | 7 0 0 | 23 | AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | 24 | | 0 0 1 | 25 | */ 26 | 27 | /** 28 | * Return an array of arrays. 29 | * Note: The returned array must be malloced, assume caller calls free(). 30 | */ 31 | int** multiply(int** A, int ARowSize, int AColSize, int** B, int BRowSize, int BColSize) { 32 |    int **result, *buff; 33 |    int i, j, k; 34 |     35 |    result = malloc(ARowSize * sizeof(int *)); 36 |    //assert(result); 37 |    for (i = 0; i < ARowSize; i ++) { 38 |        buff = calloc(BColSize, sizeof(int)); 39 |        //assert(buff); 40 |        result[i] = buff; 41 |        for (j = 0; j < AColSize; j ++) { 42 |            if (A[i][j] != 0) { 43 |                //printf("\nAij: %d\n", A[i][j]); 44 |                for (k = 0; k < BColSize; k ++) { 45 |                    //printf("Bjk: %d, ", B[j][k]); 46 |                    buff[k] += A[i][j] * B[j][k]; 47 |               } 48 |           } 49 |       } 50 |   } 51 |     52 |    return result; 53 | } 54 | 55 | 56 | /* 57 | Difficulty:Medium 58 | Total Accepted:30.5K 59 | Total Submissions:60.1K 60 | 61 | 62 | Companies LinkedIn Facebook 63 | Related Topics Hash Table 64 | 65 | */ 66 | -------------------------------------------------------------------------------- /322. Coin Change.c: -------------------------------------------------------------------------------- 1 | /* 2 | 322. Coin Change 3 | 4 | You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 5 | 6 | Example 1: 7 | 8 | Input: coins = [1, 2, 5], amount = 11 9 | Output: 3 10 | Explanation: 11 = 5 + 5 + 1 11 | 12 | Example 2: 13 | 14 | Input: coins = [2], amount = 3 15 | Output: -1 16 | 17 | 18 | Note: 19 | You may assume that you have an infinite number of each kind of coin. 20 | */ 21 | 22 | int coinChange(int* coins, int coinsSize, int amount) { 23 |    int *dp, i, j, d, n; 24 |     25 |    // can sort the coins first 26 |    // amount = amount % the biggest coin 27 |     28 |    dp = malloc((amount + 1) * sizeof(int)); 29 |    //assert(dp); 30 |    dp[0] = 0; 31 |     32 |    for (i = 1; i <= amount; i ++) { 33 |        n = -1; 34 |        for (j = 0; j < coinsSize; j ++) { 35 |            if (i >= coins[j]) { 36 |                d = i - coins[j]; 37 |                if (dp[d] != -1 && (n == -1 || n > dp[d] + 1)) { 38 |                    n = dp[d] + 1;  // plus one of this coin 39 |               } 40 |           } 41 |       } 42 |        dp[i] = n; 43 |   } 44 | 45 |    n = dp[amount]; 46 |     47 |    free(dp); 48 |     49 |    return n; 50 | } 51 | 52 | 53 | /* 54 | Difficulty:Medium 55 | 56 | 57 | */ 58 | -------------------------------------------------------------------------------- /326. Power of Three.c: -------------------------------------------------------------------------------- 1 | /* 2 | 326. Power of Three 3 | 4 | Given an integer, write a function to determine if it is a power of three. 5 | 6 | 7 | Follow up: 8 | Could you do it without using any loop / recursion? 9 | 10 | 11 | Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases. 12 | */ 13 | 14 | bool isPowerOfThree(int n) { 15 | #if 0 16 |    if (n == 1) return true; 17 |    if (n == 0 || n % 3) return false; 18 |    return isPowerOfThree(n / 3); 19 | #else 20 |    return (n > 0 && (1162261467 % n) == 0); 21 | #endif 22 | } 23 | 24 | 25 | /* 26 | Difficulty:Easy 27 | Total Accepted:99.4K 28 | Total Submissions:247.2K 29 | 30 | 31 | Companies Google 32 | Related Topics Math 33 | Similar Questions 34 | 35 | 36 | Power of Two 37 | 38 | Power of Four 39 | */ 40 | -------------------------------------------------------------------------------- /33. Search in Rotated Sorted Array.c: -------------------------------------------------------------------------------- 1 | /* 2 | 33. Search in Rotated Sorted Array 3 | 4 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | 6 | (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 7 | 8 | You are given a target value to search. If found in the array return its index, otherwise return -1. 9 | 10 | You may assume no duplicate exists in the array. 11 | */ 12 | 13 | int search(int* nums, int numsSize, int target) { 14 |    int start, end, mid; 15 |    start = 0; end = numsSize - 1; 16 |    while (start <= end) { 17 |        mid = start + (end - start) / 2; 18 |        if (nums[mid] == target) return mid; 19 |        if (nums[start] <= nums[mid]) { // first half are sorted 20 |            if (target  >  nums[mid] || target < nums[start]) { 21 |                start = mid + 1; 22 |           } else { 23 |                end = mid - 1; 24 |           } 25 |       } else { // second half are sorted 26 |            if (target < nums[mid] || target > nums[end]) { 27 |                end = mid - 1; 28 |           } else { 29 |                start = mid + 1; 30 |           } 31 |       } 32 |   } 33 |    return -1; 34 | } 35 | 36 | 37 | /* 38 | Difficulty:Medium 39 | Total Accepted:184.4K 40 | Total Submissions:574K 41 | 42 | 43 | Companies LinkedIn Bloomberg Uber Facebook Microsoft 44 | Related Topics Binary Search Array 45 | Similar Questions 46 | 47 | 48 | Search in Rotated Sorted Array II 49 | 50 | Find Minimum in Rotated Sorted Array 51 | */ 52 | -------------------------------------------------------------------------------- /334. Increasing Triplet Subsequence.c: -------------------------------------------------------------------------------- 1 | /* 2 | 334. Increasing Triplet Subsequence 3 | 4 | Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. 5 | 6 | 7 | Formally the function should: 8 | Return true if there exists i, j, k 9 | such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 10 | else return false. 11 | 12 | 13 | 14 | Your algorithm should run in O(n) time complexity and O(1) space complexity. 15 | 16 | 17 | Examples: 18 | Given [1, 2, 3, 4, 5], 19 | return true. 20 | 21 | 22 | Given [5, 4, 3, 2, 1], 23 | return false. 24 | 25 | 26 | Credits:Special thanks to @DjangoUnchained for adding this problem and creating all test cases. 27 | */ 28 | 29 | bool increasingTriplet(int* nums, int numsSize) { 30 |    int min1, min2, i, k; 31 |     32 |    min1 = min2 = 0x7fffffff; 33 |     34 |    for (i = 0; i < numsSize; i ++) { 35 |        k = nums[i]; 36 |        if (k <= min1) { 37 |            min1 = k; 38 |       } else if (k <= min2) { 39 |            min2 = k; 40 |       } else { 41 |            return true; 42 |       } 43 |   } 44 |     45 |    return false; 46 | } 47 | 48 | 49 | /* 50 | Difficulty:Medium 51 | Total Accepted:43.3K 52 | Total Submissions:110.5K 53 | 54 | 55 | Companies Facebook 56 | Similar Questions Longest Increasing Subsequence 57 | 58 | */ 59 | -------------------------------------------------------------------------------- /338. Counting Bits.c: -------------------------------------------------------------------------------- 1 | /* 2 | 338. Counting Bits 3 | 4 | Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. 5 | 6 | 7 | Example: 8 | For num = 5 you should return [0,1,1,2,1,2]. 9 | 10 | 11 | Follow up: 12 | 13 | It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? 14 | Space complexity should be O(n). 15 | Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. 16 | 17 | 18 | 19 | Credits:Special thanks to @ syedee for adding this problem and creating all test cases. 20 | */ 21 | 22 | /** 23 | * Return an array of size *returnSize. 24 | * Note: The returned array must be malloced, assume caller calls free(). 25 | */ 26 | int* countBits(int num, int* returnSize) { 27 | int *p, i; 28 | 29 | p = malloc((num + 1) * sizeof(int)); 30 | //assert(p); 31 | *returnSize = num + 1; 32 | 33 | p[0] = 0; 34 | for (i = 1; i <= num; i ++) { 35 | p[i] = p[i & (i - 1)] + 1; // i & (i - 1) is to remove a bit from tail 36 | } 37 | 38 | return p; 39 | } 40 | 41 | 42 | /* 43 | Difficulty:Medium 44 | Total Accepted:84.7K 45 | Total Submissions:138.2K 46 | 47 | 48 | Related Topics Dynamic Programming Bit Manipulation 49 | Similar Questions Number of 1 Bits 50 | 51 | */ 52 | -------------------------------------------------------------------------------- /34. Search for a Range.c: -------------------------------------------------------------------------------- 1 | /* 2 | 34. Search for a Range 3 | 4 | Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. 5 | 6 | Your algorithm's runtime complexity must be in the order of O(log n). 7 | 8 | If the target is not found in the array, return [-1, -1]. 9 | 10 | 11 | For example, 12 | Given [5, 7, 7, 8, 8, 10] and target value 8, 13 | return [3, 4]. 14 | */ 15 | 16 | /** 17 | * Return an array of size *returnSize. 18 | * Note: The returned array must be malloced, assume caller calls free(). 19 | */ 20 | int* searchRange(int* nums, int numsSize, int target, int* returnSize) { 21 | int i, j, *range; 22 | int start, end, mid; 23 | 24 | range = malloc(2 * sizeof(int)); 25 | //assert(range); 26 | 27 | i = j = -1; 28 | start = 0; end = numsSize - 1; 29 | while (start <= end) { 30 | mid = start + (end - start) / 2; 31 | if (nums[mid] == target) { 32 | i = j = mid; 33 | while (i > 0 && nums[i - 1] == target) { 34 | i --; 35 | } 36 | while (j < numsSize - 1 && nums[j + 1] == target) { 37 | j ++; 38 | } 39 | break; 40 | } else if (nums[mid] < target) { 41 | start = mid + 1; 42 | } else { 43 | end = mid - 1; 44 | } 45 | } 46 | 47 | range[0] = i; 48 | range[1] = j; 49 | 50 | *returnSize = 2; 51 | 52 | return range; 53 | } 54 | 55 | 56 | /* 57 | Difficulty:Medium 58 | Total Accepted:145.4K 59 | Total Submissions:463.3K 60 | 61 | 62 | Companies LinkedIn 63 | Related Topics Binary Search Array 64 | Similar Questions 65 | 66 | 67 | First Bad Version 68 | */ 69 | -------------------------------------------------------------------------------- /342. Power of Four.c: -------------------------------------------------------------------------------- 1 | /* 2 | 342. Power of Four 3 | 4 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 5 | 6 | Example: 7 | Given num = 16, return true. 8 | Given num = 5, return false. 9 | 10 | 11 | Follow up: Could you solve it without loops/recursion? 12 | 13 | Credits:Special thanks to @yukuairoy for adding this problem and creating all test cases. 14 | */ 15 | 16 | bool isPowerOfFour(int num) { 17 |    // one bit only and has to be on 0101 0101 0101 0101 18 |    return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0; 19 | } 20 | 21 | 22 | /* 23 | Difficulty:Easy 24 | Total Accepted:67.8K 25 | Total Submissions:176.4K 26 | 27 | 28 | Companies Two Sigma 29 | Related Topics Bit Manipulation 30 | Similar Questions 31 | 32 | 33 | Power of Two 34 | 35 | Power of Three 36 | */ 37 | -------------------------------------------------------------------------------- /344. Reverse String.c: -------------------------------------------------------------------------------- 1 | /* 2 | 344. Reverse String 3 | 4 | Write a function that takes a string as input and returns the string reversed. 5 | 6 | 7 | Example: 8 | Given s = "hello", return "olleh". 9 | */ 10 | 11 | char* reverseString(char* s) { 12 |    int i = 0; 13 |    int j; 14 |    char c; 15 |     16 |    if (!s) return s; 17 |    j = strlen(s); 18 |    if (j < 2) return s; 19 |     20 |    j --; 21 |    while (i < j) { 22 |        c = s[j]; 23 |        s[j] = s[i]; 24 |        s[i] = c; 25 |        i ++; 26 |        j --; 27 |   } 28 |    return s; 29 | } 30 | 31 | 32 | /* 33 | Difficulty:Easy 34 | Total Accepted:172.7K 35 | Total Submissions:291.9K 36 | 37 | 38 | Related Topics Two Pointers String 39 | Similar Questions Reverse Vowels of a String Reverse String II 40 | 41 | */ 42 | -------------------------------------------------------------------------------- /345. Reverse Vowels of a String.c: -------------------------------------------------------------------------------- 1 | /* 2 | 345. Reverse Vowels of a String 3 | 4 | Write a function that takes a string as input and reverse only the vowels of a string. 5 | 6 | 7 | Example 1: 8 | Given s = "hello", return "holle". 9 | 10 | 11 | 12 | Example 2: 13 | Given s = "leetcode", return "leotcede". 14 | 15 | 16 | 17 | Note: 18 | The vowels does not include the letter "y". 19 | */ 20 | 21 | #define IS_VOWEL(C) ((C) == 'a' || (C) == 'A' || \ 22 | (C) == 'e' || (C) == 'E' || \ 23 | (C) == 'i' || (C) == 'I' || \ 24 | (C) == 'o' || (C) == 'O' || \ 25 | (C) == 'u' || (C) == 'U') 26 | 27 | char* reverseVowels(char* s) { 28 | char *a, *b; 29 | 30 | if (!s || !*s) return s; 31 | 32 | a = s; 33 | b = &s[strlen(s) - 1]; 34 | 35 | while (a < b) { 36 | if (IS_VOWEL(*a) && IS_VOWEL(*b)) { 37 | // swap 38 | *a = *a ^ *b; 39 | *b = *a ^ *b; 40 | *a = *a ^ *b; 41 | a ++; 42 | b --; 43 | } else if (IS_VOWEL(*a)) { 44 | b --; 45 | } else if (IS_VOWEL(*b)) { 46 | a ++; 47 | } else { 48 | a ++; 49 | b --; 50 | } 51 | } 52 | return s; 53 | } 54 | 55 | /* 56 | Difficulty:Easy 57 | Total Accepted:82.8K 58 | Total Submissions:215.1K 59 | 60 | 61 | Companies Google 62 | Related Topics Two Pointers String 63 | Similar Questions 64 | 65 | 66 | Reverse String 67 | */ 68 | -------------------------------------------------------------------------------- /346. Moving Average from Data Stream.c: -------------------------------------------------------------------------------- 1 | /* 2 | 346. Moving Average from Data Stream 3 | 4 | Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 5 | 6 | For example, 7 | MovingAverage m = new MovingAverage(3); 8 | m.next(1) = 1 9 | m.next(10) = (1 + 10) / 2 10 | m.next(3) = (1 + 10 + 3) / 3 11 | m.next(5) = (10 + 3 + 5) / 3 12 | */ 13 | 14 | typedef struct { 15 |    int *data; 16 |    int sum; 17 |    int n; 18 |    int size; 19 | } MovingAverage; 20 | ​ 21 | /** Initialize your data structure here. */ 22 | MovingAverage* movingAverageCreate(int size) { 23 |    int *p; 24 |    MovingAverage *m; 25 |     26 |    m = calloc(1, sizeof(*m)); 27 |    p = calloc(size, sizeof(*p)); 28 |    //assert(m && p); 29 |    m->data = p; 30 |    m->sum = 0; 31 |    m->n = 0; 32 |    m->size = size; 33 |     34 |    return m; 35 | } 36 | ​ 37 | double movingAverageNext(MovingAverage* obj, int val) { 38 |    int *slot, old; 39 |     40 |    slot = &obj->data[obj->n % obj->size]; 41 |    old = *slot; 42 |    *slot = val; 43 |    obj->n ++; 44 |    obj->sum = obj->sum - old + val; 45 |     46 |    if (obj->n < obj->size) return (double)obj->sum / (double)obj->n; 47 |     48 |    return (double)obj->sum / (double)obj->size; 49 | } 50 | ​ 51 | void movingAverageFree(MovingAverage* obj) { 52 |    free(obj->data); 53 |    free(obj); 54 | } 55 | ​ 56 | /** 57 | * Your MovingAverage struct will be instantiated and called as such: 58 | * struct MovingAverage* obj = movingAverageCreate(size); 59 | * double param_1 = movingAverageNext(obj, val); 60 | * movingAverageFree(obj); 61 | */ 62 | 63 | 64 | /* 65 | Difficulty:Easy 66 | Total Accepted:25.3K 67 | Total Submissions:43K 68 | 69 | 70 | Companies Google 71 | Related Topics Design Queue 72 | 73 | */ 74 | -------------------------------------------------------------------------------- /367. Valid Perfect Square.c: -------------------------------------------------------------------------------- 1 | /* 2 | 367. Valid Perfect Square 3 | 4 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 5 | 6 | 7 | Note: Do not use any built-in library function such as sqrt. 8 | 9 | 10 | Example 1: 11 | Input: 16 12 | Returns: True 13 | 14 | 15 | 16 | Example 2: 17 | Input: 14 18 | Returns: False 19 | 20 | 21 | 22 | Credits:Special thanks to @elmirap for adding this problem and creating all test cases. 23 | */ 24 | 25 | bool isPerfectSquare(unsigned int num) { 26 | #define MAX_SQRT 46341 27 |    unsigned int start = 1, end, mid, k; 28 |    end = num < MAX_SQRT ? num : MAX_SQRT; 29 |    while (start <= end) { 30 |        mid = start + (end - start) / 2; 31 |        k = mid * mid; 32 |        //printf("%d:%d\n", mid, k); 33 |        if (k == num) return true; 34 |        else if (k > num) end = mid - 1; 35 |        else start = mid + 1; 36 |   } 37 |    return false; 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Easy 43 | Total Accepted:49.4K 44 | Total Submissions:129.3K 45 | 46 | 47 | Companies LinkedIn 48 | Related Topics Binary Search Math 49 | Similar Questions 50 | 51 | 52 | Sqrt(x) 53 | 54 | Sum of Square Numbers 55 | */ 56 | -------------------------------------------------------------------------------- /369. Plus One Linked List.c: -------------------------------------------------------------------------------- 1 | /* 2 | 369. Plus One Linked List 3 | 4 | Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer. 5 | 6 | You may assume the integer do not contain any leading zero, except the number 0 itself. 7 | 8 | The digits are stored such that the most significant digit is at the head of the list. 9 | 10 | Example: 11 | Input: 12 | 1->2->3 13 | 14 | Output: 15 | 1->2->4 16 | */ 17 | 18 | /** 19 | * Definition for singly-linked list. 20 | * struct ListNode { 21 | *     int val; 22 | *     struct ListNode *next; 23 | * }; 24 | */ 25 | int plus(struct ListNode *node) { 26 |    int one; 27 |    if (!node->next) { 28 |        one = (node->val + 1) / 10; 29 |        node->val = (node->val + 1) % 10; 30 |        return one; 31 |   } 32 |    one = plus(node->next); 33 |    if (one) { 34 |        one = (node->val + 1) / 10; 35 |        node->val = (node->val + 1) % 10; 36 |   } 37 |    return one; 38 | } 39 | struct ListNode* plusOne(struct ListNode* head) { 40 |    struct ListNode *node = head; 41 |    int one = plus(node); 42 |    if (one) { 43 |        node = malloc(sizeof(struct ListNode)); 44 |        //assert(node); 45 |        node->val = 1; 46 |        node->next = head; 47 |   } 48 |    return node; 49 | } 50 | 51 | 52 | /* 53 | Difficulty:Medium 54 | Total Accepted:16K 55 | Total Submissions:29.5K 56 | 57 | 58 | Companies Google 59 | Related Topics Linked List 60 | Similar Questions 61 | 62 | 63 | Plus One 64 | */ 65 | -------------------------------------------------------------------------------- /38. Count and Say.c: -------------------------------------------------------------------------------- 1 | /* 2 | 38. Count and Say 3 | 4 | The count-and-say sequence is the sequence of integers with the first five terms as following: 5 | 1. 1 6 | 2. 11 7 | 3. 21 8 | 4. 1211 9 | 5. 111221 10 | 11 | 12 | 13 | 1 is read off as "one 1" or 11. 14 | 11 is read off as "two 1s" or 21. 15 | 21 is read off as "one 2, then one 1" or 1211. 16 | 17 | 18 | 19 | Given an integer n, generate the nth term of the count-and-say sequence. 20 | 21 | 22 | 23 | Note: Each term of the sequence of integers will be represented as a string. 24 | 25 | 26 | Example 1: 27 | Input: 1 28 | Output: "1" 29 | 30 | 31 | 32 | Example 2: 33 | Input: 4 34 | Output: "1211" 35 | */ 36 | 37 | char* countAndSay(int n) { 38 |    char *s, *d, *x; 39 |    int i, c; 40 |     41 |    if (!n) return NULL; 42 |     43 | #define BUF_SIZE 100 * 1024 44 |     45 |    s = malloc(BUF_SIZE); 46 |    x = d = malloc(BUF_SIZE); 47 |    s[0] = '1'; 48 |    s[1] = 0; 49 |     50 |    while (n > 1) { 51 |        c = 1; 52 |        for (i = 0; s[i]; i ++) { 53 |            if (s[i] != s[i+1]) { 54 |                sprintf(x, "%d%c", c, s[i]); 55 |                x += strlen(x); 56 |                c = 1; 57 |           } else { 58 |                c ++; 59 |           } 60 |       } 61 |        x = s; 62 |        s = d; 63 |        d = x; 64 |        n --; 65 |   } 66 |     67 |    free(d); 68 |    return s; 69 | } 70 | 71 | 72 | /* 73 | Difficulty:Easy 74 | Total Accepted:145.1K 75 | Total Submissions:418.7K 76 | 77 | 78 | Companies Facebook 79 | Related Topics String 80 | Similar Questions 81 | 82 | 83 | Encode and Decode Strings 84 | */ 85 | -------------------------------------------------------------------------------- /383. Ransom Note.c: -------------------------------------------------------------------------------- 1 | /* 2 | 383. Ransom Note 3 | 4 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom 5 | note can be constructed from the magazines ; otherwise, it will return false. 6 | 7 | 8 | Each letter in the magazine string can only be used once in your ransom note. 9 | 10 | 11 | Note: 12 | You may assume that both strings contain only lowercase letters. 13 | 14 | 15 | canConstruct("a", "b") -> false 16 | canConstruct("aa", "ab") -> false 17 | canConstruct("aa", "aab") -> true 18 | */ 19 | 20 | bool canConstruct(char* ransomNote, char* magazine) { 21 |    int i, t = 0, n[26] = { 0 }; 22 |     23 |    while (ransomNote && *ransomNote) { 24 |        i = *ransomNote - 'a'; 25 |        n[i] ++; 26 |        t ++; 27 |        ransomNote ++; 28 |   } 29 |     30 |    while (magazine && *magazine) { 31 |        i = *magazine - 'a'; 32 |        if (n[i]) { 33 |            n[i] --; 34 |            t --; 35 |       } 36 |        magazine ++; 37 |   } 38 |     39 |    if (t) return false; 40 |     41 |    return true; 42 | } 43 | 44 | 45 | /* 46 | Difficulty:Easy 47 | Total Accepted:58.8K 48 | Total Submissions:124.9K 49 | 50 | 51 | Companies Apple 52 | Related Topics String 53 | 54 | */ 55 | -------------------------------------------------------------------------------- /387. First Unique Character in a String.c: -------------------------------------------------------------------------------- 1 | /* 2 | 387. First Unique Character in a String 3 | 4 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 5 | 6 | Examples: 7 | s = "leetcode" 8 | return 0. 9 | 10 | s = "loveleetcode", 11 | return 2. 12 | 13 | 14 | 15 | 16 | Note: You may assume the string contain only lowercase letters. 17 | */ 18 | 19 | int firstUniqChar(char* s) { 20 |    int num[26] = { 0 }; 21 |    int idx[26]; 22 |    int i, j; 23 |     24 |    i = 0; 25 |    while (s[i]) { 26 |        num[s[i] - 'a'] ++; 27 |        idx[s[i] - 'a'] = i; 28 |        i ++; 29 |   } 30 |    j = -1; 31 |    for (i = 0; i < 26; i ++) { 32 |        if (num[i] == 1 && (j == -1 || j > idx[i])) { 33 |            j = idx[i]; 34 |       } 35 |   } 36 |    return j; 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Easy 42 | Total Accepted:70.1K 43 | Total Submissions:150.5K 44 | 45 | 46 | Companies Amazon Bloomberg Microsoft 47 | 48 | */ 49 | -------------------------------------------------------------------------------- /389. Find the Difference.c: -------------------------------------------------------------------------------- 1 | /* 2 | 389. Find the Difference 3 | 4 | Given two strings s and t which consist of only lowercase letters. 5 | 6 | String t is generated by random shuffling string s and then add one more letter at a random position. 7 | 8 | Find the letter that was added in t. 9 | 10 | Example: 11 | Input: 12 | s = "abcd" 13 | t = "abcde" 14 | 15 | Output: 16 | e 17 | 18 | Explanation: 19 | 'e' is the letter that was added. 20 | */ 21 | 22 | char findTheDifference(char* s, char* t) { 23 | #if 0 24 |    int i, n[26] = { 0 }; 25 |    while (*s) { 26 |        n[*s - 'a'] ++; 27 |        n[*t - 'a'] --; 28 |        s ++; 29 |        t ++; 30 |   } 31 |    n[*t - 'a'] --; 32 |    for (i = 0; i < 26; i ++) { 33 |        if (n[i]) return i + 'a'; 34 |   } 35 |    return 0; 36 | #else 37 |    char c = t[0]; 38 |    t ++; 39 |    while (*s) { 40 |        c = c ^ *s ^ *t; 41 |        s ++; 42 |        t ++; 43 |   } 44 |    return c; 45 | #endif 46 | } 47 | 48 | 49 | /* 50 | Difficulty:Easy 51 | Total Accepted:77.4K 52 | Total Submissions:152.9K 53 | 54 | 55 | Companies Google 56 | Related Topics Hash Table Bit Manipulation 57 | Similar Questions 58 | 59 | 60 | Single Number 61 | */ 62 | -------------------------------------------------------------------------------- /397. Integer Replacement.c: -------------------------------------------------------------------------------- 1 | /* 2 | 397. Integer Replacement 3 | 4 | Given a positive integer n and you can do operations as follow: 5 | 6 | 7 | 8 | 9 | If n is even, replace n with n/2. 10 | If n is odd, you can replace n with either n + 1 or n - 1. 11 | 12 | 13 | 14 | 15 | What is the minimum number of replacements needed for n to become 1? 16 | 17 | 18 | 19 | 20 | Example 1: 21 | Input: 22 | 8 23 | 24 | Output: 25 | 3 26 | 27 | Explanation: 28 | 8 -> 4 -> 2 -> 1 29 | 30 | 31 | 32 | Example 2: 33 | Input: 34 | 7 35 | 36 | Output: 37 | 4 38 | 39 | Explanation: 40 | 7 -> 8 -> 4 -> 2 -> 1 41 | or 42 | 7 -> 6 -> 3 -> 2 -> 1 43 | */ 44 | 45 | int integerReplacement(int n) { 46 |    int k = 0; 47 |    while (n != 1) { 48 |        if (n & 1) { 49 |            if ((n & 3) == 3 && n > 3) { 50 |                n += 1; 51 |           } else { 52 |                n -= 1; 53 |           } 54 |       } else { 55 |            n = (n >> 1) & 0x7fffffff; 56 |       } 57 |        k ++; 58 |   } 59 |    return k; 60 | } 61 | 62 | 63 | /* 64 | Difficulty:Medium 65 | Total Accepted:21.8K 66 | Total Submissions:72.3K 67 | 68 | 69 | Companies Google Baidu 70 | Related Topics Math Bit Manipulation 71 | 72 | */ 73 | -------------------------------------------------------------------------------- /400. Nth Digit.c: -------------------------------------------------------------------------------- 1 | /* 2 | 400. Nth Digit 3 | 4 | Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 5 | 6 | Note: 7 | n is positive and will fit within the range of a 32-bit signed integer (n < 231). 8 | 9 | 10 | Example 1: 11 | Input: 12 | 3 13 | 14 | Output: 15 | 3 16 | 17 | 18 | 19 | Example 2: 20 | Input: 21 | 11 22 | 23 | Output: 24 | 0 25 | 26 | Explanation: 27 | The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. 28 | */ 29 | 30 | int findNthDigit(int n) { 31 |    unsigned int i, j, k; 32 | ​ 33 |    i = j = 1; 34 |    while (n > 9 * i * j) { 35 |        n -= 9 * i * j; 36 |        j *= 10; 37 |        i ++; 38 |   } 39 |    k = j + (n - 1) / i; 40 |    for (j = (n - 1) % i; j < i - 1; j ++) { 41 |        k = k / 10; 42 |   } 43 |    return k % 10; 44 | } 45 | 46 | 47 | /* 48 | Difficulty:Easy 49 | Total Accepted:25K 50 | Total Submissions:83.1K 51 | 52 | 53 | Companies Google 54 | Related Topics Math 55 | 56 | */ 57 | -------------------------------------------------------------------------------- /404. Sum of Left Leaves.c: -------------------------------------------------------------------------------- 1 | /* 2 | 404. Sum of Left Leaves 3 | 4 | Find the sum of all left leaves in a given binary tree. 5 | 6 | Example: 7 | 3 8 | / \ 9 | 9 20 10 | / \ 11 | 15 7 12 | 13 | There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 14 | */ 15 | 16 | /** 17 | * Definition for a binary tree node. 18 | * struct TreeNode { 19 | *     int val; 20 | *     struct TreeNode *left; 21 | *     struct TreeNode *right; 22 | * }; 23 | */ 24 | void sumleft(struct TreeNode *node, int *n, int left) { 25 |    if (!node) return; 26 |    sumleft(node->left, n, 1); 27 |    if (left && !node->left && !node->right) *n += node->val; 28 |    sumleft(node->right, n, 0); 29 | } 30 | int sumOfLeftLeaves(struct TreeNode* root) { 31 |    int n = 0; 32 |    sumleft(root, &n, 0); 33 |    return n; 34 | } 35 | 36 | 37 | /* 38 | Difficulty:Easy 39 | Total Accepted:58.9K 40 | Total Submissions:125.6K 41 | 42 | 43 | Companies Facebook 44 | Related Topics Tree 45 | 46 | */ 47 | -------------------------------------------------------------------------------- /408. Valid Word Abbreviation.c: -------------------------------------------------------------------------------- 1 | /* 2 | 408. Valid Word Abbreviation 3 | 4 | Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation. 5 | 6 | 7 | A string such as "word" contains only the following valid abbreviations: 8 | 9 | ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] 10 | 11 | 12 | Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word". 13 | 14 | Note: 15 | Assume s contains only lowercase letters and abbr contains only lowercase letters and digits. 16 | 17 | 18 | Example 1: 19 | Given s = "internationalization", abbr = "i12iz4n": 20 | 21 | Return true. 22 | 23 | 24 | 25 | Example 2: 26 | Given s = "apple", abbr = "a2e": 27 | 28 | Return false. 29 | */ 30 | 31 | bool validWordAbbreviation(char* word, char* abbr) { 32 |    int n = 0; 33 |    while (*abbr) { 34 |        if (*abbr >= '0' && *abbr <= '9') { 35 |            n = n * 10 + *abbr - '0'; 36 |            if (!n) return false; // invalid input 37 |       } else { 38 |            while (n && *word) { 39 |                n --; word ++; 40 |           } 41 |            if (*word != *abbr) return false; 42 |            word ++; 43 |       } 44 |        abbr ++; 45 |   } 46 |    while (n && *word) { 47 |        n --; word ++; 48 |   } 49 |    return (n || *word) ? false : true; 50 | } 51 | 52 | 53 | /* 54 | Difficulty:Easy 55 | Total Accepted:11.1K 56 | Total Submissions:39.6K 57 | 58 | 59 | Companies Google 60 | Related Topics String 61 | Similar Questions 62 | 63 | 64 | Minimum Unique Word Abbreviation 65 | 66 | Word Abbreviation 67 | */ 68 | -------------------------------------------------------------------------------- /409. Longest Palindrome.c: -------------------------------------------------------------------------------- 1 | /* 2 | 409. Longest Palindrome 3 | 4 | Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. 5 | 6 | This is case sensitive, for example "Aa" is not considered a palindrome here. 7 | 8 | Note: 9 | Assume the length of given string will not exceed 1,010. 10 | 11 | 12 | Example: 13 | Input: 14 | "abccccdd" 15 | 16 | Output: 17 | 7 18 | 19 | Explanation: 20 | One longest palindrome that can be built is "dccaccd", whose length is 7. 21 | */ 22 | 23 | int longestPalindrome(char* s) { 24 |    int n[52] = { 0 }; 25 |    int i, k, odd; 26 |    while (*s) { 27 |        if (*s >= 'a') i = *s - 'a'; 28 |        else           i = *s - 'A' + 26; 29 |        n[i] ++; 30 |        s ++; 31 |   } 32 |    k = 0; 33 |    odd = 0; 34 |    for (i = 0; i < 52; i ++) { 35 |        odd |= n[i] % 2; 36 |        k += n[i] - (n[i] % 2); // can use part of them!!! 37 |   } 38 |    return k + odd; 39 | } 40 | 41 | 42 | /* 43 | Difficulty:Easy 44 | Total Accepted:45.6K 45 | Total Submissions:100.4K 46 | 47 | 48 | Companies Google 49 | Related Topics Hash Table 50 | Similar Questions 51 | 52 | 53 | Palindrome Permutation 54 | */ 55 | -------------------------------------------------------------------------------- /41. First Missing Positive.c: -------------------------------------------------------------------------------- 1 | /* 2 | 41. First Missing Positive 3 | 4 | Given an unsorted integer array, find the first missing positive integer. 5 | 6 | 7 | 8 | For example, 9 | Given [1,2,0] return 3, 10 | and [3,4,-1,1] return 2. 11 | 12 | 13 | 14 | Your algorithm should run in O(n) time and uses constant space. 15 | */ 16 | 17 | int firstMissingPositive(int* nums, int numsSize) { 18 |    int i, k, t; 19 |    for (i = 0; i < numsSize; i ++) { 20 |        k = nums[i]; 21 |        while (k > 0 && k < numsSize && k != nums[k - 1]) { 22 |            nums[i] = nums[k - 1]; 23 |            nums[k - 1] = k; 24 |            k = nums[i]; 25 |       } 26 |   } 27 |    for (i = 0; i < numsSize; i ++) { 28 |        if (nums[i] != i + 1) break; 29 |   } 30 |    return i + 1; 31 | } 32 | 33 | 34 | /* 35 | Difficulty:Hard 36 | Total Accepted:104.4K 37 | Total Submissions:409.1K 38 | 39 | 40 | Related Topics Array 41 | Similar Questions Missing Number Find the Duplicate Number Find All Numbers Disappeared in an Array 42 | 43 | */ 44 | -------------------------------------------------------------------------------- /415. Add Strings.c: -------------------------------------------------------------------------------- 1 | /* 2 | 415. Add Strings 3 | 4 | Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. 5 | 6 | Note: 7 | 8 | The length of both num1 and num2 is < 5100. 9 | Both num1 and num2 contains only digits 0-9. 10 | Both num1 and num2 does not contain any leading zero. 11 | You must not use any built-in BigInteger library or convert the inputs to integer directly. 12 | */ 13 | 14 | char* addStrings(char* num1, char* num2) { 15 |    int one, k, i; 16 |    int l1 = strlen(num1); 17 |    int l2 = strlen(num2); 18 |    int l = l1 > l2 ? l1 : l2; 19 |    char c1, c2; 20 |    char *s, *buff; 21 |     22 |    buff = malloc((l + 2) * sizeof(char)); 23 |    //assert(buff); 24 |     25 |    i = l + 2; 26 |    buff[-- i] = 0;  // null terminated 27 |    one = 0; 28 |    while (l1 > 0 || l2 > 0) { 29 |        c1 = l1 > 0 ? num1[-- l1] : '0'; 30 |        c2 = l2 > 0 ? num2[-- l2] : '0'; 31 |        k = c1 - '0' + c2 - '0' + one; 32 |        one = k / 10; 33 |        k = k % 10; 34 |        buff[-- i] = k + '0'; 35 |   } 36 |    if (one) { 37 |        buff[-- i] = '1'; 38 |        //assert(i == 0); 39 |        s = buff; 40 |   } else { 41 |        s = malloc((l + 2) * sizeof(char)); 42 |        //assert(s); 43 |        strcpy(s, &buff[i]); 44 |        free(buff); 45 |   } 46 |    return s; 47 | } 48 | 49 | 50 | /* 51 | Difficulty:Easy 52 | Total Accepted:38.4K 53 | Total Submissions:93K 54 | 55 | 56 | Companies Google Airbnb 57 | Related Topics Math 58 | Similar Questions 59 | 60 | 61 | Add Two Numbers 62 | 63 | Multiply Strings 64 | */ 65 | -------------------------------------------------------------------------------- /416. Partition Equal Subset Sum.c: -------------------------------------------------------------------------------- 1 | /* 2 | 416. Partition Equal Subset Sum 3 | 4 | Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. 5 | 6 | 7 | Note: 8 | 9 | Each of the array element will not exceed 100. 10 | The array size will not exceed 200. 11 | 12 | 13 | 14 | Example 1: 15 | Input: [1, 5, 11, 5] 16 | 17 | Output: true 18 | 19 | Explanation: The array can be partitioned as [1, 5, 5] and [11]. 20 | 21 | 22 | 23 | Example 2: 24 | Input: [1, 2, 3, 5] 25 | 26 | Output: false 27 | 28 | Explanation: The array cannot be partitioned into equal sum subsets. 29 | */ 30 | 31 | bool canPartition(int* nums, int numsSize) { 32 | int t, s, i, k; 33 | bool *dp, ans; 34 | 35 | t = 0; 36 | for (i = 0; i < numsSize; i ++) { 37 | t += nums[i]; 38 | } 39 | 40 | if (t & 1) return false; 41 | 42 | t >>= 1; 43 | 44 | dp = calloc(t + 1, sizeof(bool)); 45 | //assert(dp); 46 | 47 | dp[0] = true; 48 | for (i = 0; !dp[t] && i < numsSize; i ++) { 49 | k = nums[i]; 50 | for (s = t; s >= k; s --) { 51 | dp[s] = dp[s - k]; 52 | } 53 | } 54 | 55 | ans = dp[t]; 56 | 57 | free(dp); 58 | 59 | return ans; 60 | } 61 | 62 | 63 | /* 64 | Difficulty:Medium 65 | Total Accepted:25.4K 66 | Total Submissions:65K 67 | 68 | 69 | Companies eBay 70 | Related Topics Dynamic Programming 71 | 72 | */ 73 | -------------------------------------------------------------------------------- /424. Longest Repeating Character Replacement.c: -------------------------------------------------------------------------------- 1 | /* 2 | 424. Longest Repeating Character Replacement 3 | 4 | Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations. 5 | 6 | Note: 7 | Both the string's length and k will not exceed 104. 8 | 9 | 10 | 11 | Example 1: 12 | Input: 13 | s = "ABAB", k = 2 14 | 15 | Output: 16 | 4 17 | 18 | Explanation: 19 | Replace the two 'A's with two 'B's or vice versa. 20 | 21 | 22 | 23 | 24 | Example 2: 25 | Input: 26 | s = "AABABBA", k = 1 27 | 28 | Output: 29 | 4 30 | 31 | Explanation: 32 | Replace the one 'A' in the middle with 'B' and form "AABBBBA". 33 | The substring "BBBB" has the longest repeating letters, which is 4. 34 | */ 35 | 36 | int characterReplacement(char* s, int k) { 37 |    int cnt[26] = { 0 }; 38 |    int i, max, start, end; 39 |     40 |    max = start = end = 0; 41 |     42 |    while (s[end]) {  // O(n) 3ms 43 |        i = s[end ++] - 'A'; 44 |        cnt[i] ++; 45 |        max = max > cnt[i] ? max : cnt[i];  // longest length of single character 46 |        if (end - start > max + k) {  // length of window exceeds the limit with all replacement 47 |            i = s[start ++] - 'A'; // shrink the window by advancing start pointer 48 |            cnt[i] --; 49 |       } 50 |   } 51 |     52 |    return end - start;  // this is the biggest window 53 | } 54 | 55 | 56 | /* 57 | Difficulty:Medium 58 | Total Accepted:13K 59 | Total Submissions:30.9K 60 | 61 | 62 | Companies Pocket Gems 63 | Similar Questions Longest Substring with At Most K Distinct Characters 64 | 65 | */ 66 | -------------------------------------------------------------------------------- /437. Path Sum III.c: -------------------------------------------------------------------------------- 1 | /* 2 | 437. Path Sum III 3 | 4 | You are given a binary tree in which each node contains an integer value. 5 | 6 | Find the number of paths that sum to a given value. 7 | 8 | The path does not need to start or end at the root or a leaf, but it must go downwards 9 | (traveling only from parent nodes to child nodes). 10 | 11 | The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. 12 | 13 | Example: 14 | root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 15 | 16 | 10 17 | / \ 18 | 5 -3 19 | / \ \ 20 | 3 2 11 21 | / \ \ 22 | 3 -2 1 23 | 24 | Return 3. The paths that sum to 8 are: 25 | 26 | 1. 5 -> 3 27 | 2. 5 -> 2 -> 1 28 | 3. -3 -> 11 29 | */ 30 | 31 | /** 32 | * Definition for a binary tree node. 33 | * struct TreeNode { 34 | *     int val; 35 | *     struct TreeNode *left; 36 | *     struct TreeNode *right; 37 | * }; 38 | */ 39 | int sumFrom(struct TreeNode *node, int sum) { 40 |    int n = 0; 41 |     42 |    if (node) { 43 |        sum -= node->val; 44 |        n += (!sum) ? 1 : 0; 45 |        n += sumFrom(node->left, sum); 46 |        n += sumFrom(node->right, sum); 47 |   } 48 |     49 |    return n; 50 | } 51 | int pathSum(struct TreeNode* root, int sum) { 52 |    if (!root) return 0; 53 |    return sumFrom(root, sum) + 54 |           pathSum(root->left, sum) + 55 |           pathSum(root->right, sum); 56 | } 57 | 58 | 59 | /* 60 | Difficulty:Easy 61 | Total Accepted:33.6K 62 | Total Submissions:84.2K 63 | 64 | 65 | Related Topics Tree 66 | Similar Questions Path Sum Path Sum II 67 | 68 | */ 69 | -------------------------------------------------------------------------------- /447. Number of Boomerangs.c: -------------------------------------------------------------------------------- 1 | /* 2 | 447. Number of Boomerangs 3 | 4 | Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). 5 | 6 | Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive). 7 | 8 | Example: 9 | Input: 10 | [[0,0],[1,0],[2,0]] 11 | 12 | Output: 13 | 2 14 | 15 | Explanation: 16 | The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]] 17 | */ 18 | 19 | #define DUMP(P, I, J, K) do { } while (0) 20 | ​ 21 | int dis(int **p, int a, int b) { 22 |    int x = abs(p[a][0] - p[b][0]); 23 |    int y = abs(p[a][1] - p[b][1]); 24 |    int z = x * x + y * y; 25 |    return z; 26 | } 27 | int numberOfBoomerangs(int** points, int pointsRowSize, int pointsColSize) { 28 |    int n = 0; 29 |    int i, j, k; 30 |    double d1, d2; 31 |    for (i = 0; i < pointsRowSize; i ++) { 32 |        for (j = 0; j < pointsRowSize; j ++) { 33 |            if (j == i) continue; 34 |            d1 = dis(points, i, j); 35 |            for (k = j + 1; k < pointsRowSize; k ++) { 36 |                d2 = dis(points, i, k); 37 |                if (d1 == d2) { 38 |                    DUMP(points, i, j, k); 39 |                    n ++; 40 |               } 41 |           } 42 |       } 43 |   } 44 |    return n * 2; 45 | } 46 | 47 | 48 | /* 49 | Difficulty:Easy 50 | Total Accepted:25K 51 | Total Submissions:55.6K 52 | 53 | 54 | Companies Google 55 | Related Topics Hash Table 56 | Similar Questions 57 | 58 | 59 | Line Reflection 60 | */ 61 | -------------------------------------------------------------------------------- /448. Find All Numbers Disappeared in an Array.c: -------------------------------------------------------------------------------- 1 | /* 2 | 448. Find All Numbers Disappeared in an Array 3 | 4 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 5 | 6 | Find all the elements of [1, n] inclusive that do not appear in this array. 7 | 8 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 9 | 10 | Example: 11 | Input: 12 | [4,3,2,7,8,2,3,1] 13 | 14 | Output: 15 | [5,6] 16 | */ 17 | 18 | /** 19 | * Return an array of size *returnSize. 20 | * Note: The returned array must be malloced, assume caller calls free(). 21 | */ 22 | int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) { 23 |    int *p; 24 |    int i, j, x; 25 |     26 |    p = malloc(numsSize * sizeof(int)); 27 |    //assert(p); 28 |    for (i = 0; i < numsSize; i ++) { 29 |        x = nums[i]; 30 |        x = (x > 0) ? x - 1 : 0 - x - 1; 31 |        if (nums[x] > 0) nums[x] = 0 - nums[x]; 32 |   } 33 |    j = 0; 34 |    for (i = 1; i <= numsSize; i ++) { 35 |        if (nums[i - 1] > 0) { 36 |            p[j ++] = i; 37 |       } 38 |   } 39 |    *returnSize = j; 40 |    return p; 41 | } 42 | 43 | 44 | /* 45 | Difficulty:Easy 46 | Total Accepted:54.4K 47 | Total Submissions:106K 48 | 49 | 50 | Companies Google 51 | Related Topics Array 52 | Similar Questions 53 | 54 | 55 | First Missing Positive 56 | 57 | Find All Duplicates in an Array 58 | */ 59 | -------------------------------------------------------------------------------- /459. Repeated Substring Pattern.c: -------------------------------------------------------------------------------- 1 | /* 2 | 459. Repeated Substring Pattern 3 | 4 | Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. 5 | 6 | Example 1: 7 | Input: "abab" 8 | 9 | Output: True 10 | 11 | Explanation: It's the substring "ab" twice. 12 | 13 | 14 | 15 | Example 2: 16 | Input: "aba" 17 | 18 | Output: False 19 | 20 | 21 | 22 | Example 3: 23 | Input: "abcabcabcabc" 24 | 25 | Output: True 26 | 27 | Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) 28 | */ 29 | 30 | bool repeatedSubstringPattern(char* str) { 31 |    int i, j, k; 32 |    int l = strlen(str); 33 |    for (i = 2; i <= l; i ++) { 34 |        if (l % i) continue; 35 |        k = l / i; 36 |        for (j = 1; j < i; j ++) { 37 |            if (strncmp(&str[0], &str[j * k], k)) break; 38 |       } 39 |        if (j == i) return true; 40 |   } 41 |    return false; 42 | } 43 | 44 | 45 | /* 46 | Difficulty:Easy 47 | Total Accepted:35K 48 | Total Submissions:91.8K 49 | 50 | 51 | Companies Amazon Google 52 | Related Topics String 53 | Similar Questions 54 | 55 | 56 | Implement strStr() 57 | */ 58 | -------------------------------------------------------------------------------- /461. Hamming Distance.c: -------------------------------------------------------------------------------- 1 | /* 2 | 461. Hamming Distance 3 | 4 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 5 | 6 | Given two integers x and y, calculate the Hamming distance. 7 | 8 | Note: 9 | 0 ≤ x, y < 231. 10 | 11 | 12 | Example: 13 | Input: x = 1, y = 4 14 | 15 | Output: 2 16 | 17 | Explanation: 18 | 1 (0 0 0 1) 19 | 4 (0 1 0 0) 20 | ? ? 21 | 22 | The above arrows point to positions where the corresponding bits are different. 23 | */ 24 | 25 | int hammingDistance(int x, int y) { 26 |    int k = x ^ y; 27 |    int n = 0; 28 |    while (k) { 29 |        n ++; 30 |        k = k & (k - 1);  // reduce one bit 31 |   } 32 |    return n; 33 | } 34 | 35 | 36 | /* 37 | Difficulty:Easy 38 | Total Accepted:85.8K 39 | Total Submissions:122.5K 40 | 41 | 42 | Companies Facebook 43 | Related Topics Bit Manipulation 44 | Similar Questions 45 | 46 | 47 | Number of 1 Bits 48 | 49 | Total Hamming Distance 50 | */ 51 | -------------------------------------------------------------------------------- /463. Island Perimeter.c: -------------------------------------------------------------------------------- 1 | /* 2 | 463. Island Perimeter 3 | 4 | You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. 5 | 6 | Example: 7 | [[0,1,0,0], 8 | [1,1,1,0], 9 | [0,1,0,0], 10 | [1,1,0,0]] 11 | 12 | Answer: 16 13 | Explanation: The perimeter is the 16 yellow stripes in the image below: 14 | */ 15 | 16 | int islandPerimeter(int** grid, int gridRowSize, int gridColSize) { 17 |    int m = 0; 18 |    int i, j; 19 |    for (i = 0; i < gridRowSize; i ++) { 20 |        for (j = 0; j < gridColSize; j ++) { 21 |            if (grid[i][j] == 1) { 22 |                if (i == 0 || grid[i - 1][j] == 0) { 23 |                    m ++; 24 |               } 25 |                if (i == gridRowSize - 1 || grid[i + 1][j] == 0) { 26 |                    m ++; 27 |               } 28 |                if (j == 0 || grid[i][j - 1] == 0) { 29 |                    m ++; 30 |               } 31 |                if (j == gridColSize - 1 || grid[i][j + 1] == 0) { 32 |                    m ++; 33 |               } 34 |           } 35 |       } 36 |   } 37 |    return m; 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Easy 43 | Total Accepted:49K 44 | Total Submissions:85.9K 45 | 46 | 47 | Companies Google 48 | Related Topics Hash Table 49 | 50 | */ 51 | -------------------------------------------------------------------------------- /476. Number Complement.c: -------------------------------------------------------------------------------- 1 | /* 2 | 476. Number Complement 3 | 4 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. 5 | 6 | Note: 7 | 8 | The given integer is guaranteed to fit within the range of a 32-bit signed integer. 9 | You could assume no leading zero bit in the integer’s binary representation. 10 | 11 | 12 | 13 | Example 1: 14 | Input: 5 15 | Output: 2 16 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. 17 | 18 | 19 | 20 | Example 2: 21 | Input: 1 22 | Output: 0 23 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. 24 | */ 25 | 26 | int findComplement(int num) { 27 |    int i, k = 0; 28 |    if (!num) return 1; 29 |    for (i = 0; num && i < 32; i ++) { 30 |        if (!(num & (1 << i))) { 31 |            k |= (1 << i); 32 |       } else { 33 |            num &= ~(1 << i); 34 |       } 35 |   } 36 |    return k; 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Easy 42 | Total Accepted:49.4K 43 | Total Submissions:81K 44 | 45 | 46 | Companies Cloudera 47 | Related Topics Bit Manipulation 48 | 49 | */ 50 | -------------------------------------------------------------------------------- /477. Total Hamming Distance.c: -------------------------------------------------------------------------------- 1 | /* 2 | 477. Total Hamming Distance 3 | 4 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 5 | 6 | Now your job is to find the total Hamming distance between all pairs of the given numbers. 7 | 8 | 9 | Example: 10 | Input: 4, 14, 2 11 | 12 | Output: 6 13 | 14 | Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just 15 | showing the four bits relevant in this case). So the answer will be: 16 | HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. 17 | 18 | 19 | 20 | Note: 21 | 22 | Elements of the given array are in the range of 0 to 10^9 23 | Length of the array will not exceed 10^4. 24 | */ 25 | 26 | int totalHammingDistance(int* nums, int numsSize) { 27 |    int i, j, k, t; 28 |    t = 0; 29 |    for (i = 0; i < 32; i ++) {  // for every bit 30 |        k = 0; 31 |        for (j = 0; j < numsSize; j ++) { 32 |            k += (nums[j] & (1 << i)) ? 1 : 0;  // number of bit 1 33 |       } 34 |        t += k * (numsSize - k);  // distance on this particular bit 35 |   } 36 |    return t; 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Medium 42 | Total Accepted:18.8K 43 | Total Submissions:40.3K 44 | 45 | 46 | Companies Facebook 47 | Related Topics Bit Manipulation 48 | Similar Questions 49 | 50 | 51 | Hamming Distance 52 | */ 53 | -------------------------------------------------------------------------------- /48. Rotate Image.c: -------------------------------------------------------------------------------- 1 | /* 2 | 48. Rotate Image 3 | 4 | You are given an n x n 2D matrix representing an image. 5 | Rotate the image by 90 degrees (clockwise). 6 | Follow up: 7 | Could you do this in-place? 8 | */ 9 | 10 | #define RIGHT(I)   (matrix[I][y]) 11 | #define BOTTOM(I)   (matrix[y][y + x - I]) 12 | #define LEFT(I)     (matrix[y + x - I][x]) 13 | #define TOP(I)     (matrix[x][I]) 14 | ​ 15 | void spin(int **matrix, int x, int y) { 16 |    int i; 17 |    int a, b, c; 18 |     19 |    if (x >= y) return; 20 |     21 |    for (i = x; i < y; i ++) { 22 |        a = RIGHT(i); 23 |        RIGHT(i) = TOP(i); 24 |         25 |        b = BOTTOM(i); 26 |        BOTTOM(i) = a; 27 |         28 |        c = LEFT(i); 29 |        LEFT(i) = b; 30 |         31 |        TOP(i) = c; 32 |   } 33 |    spin(matrix, x + 1, y - 1); 34 | } 35 | void rotate(int** matrix, int matrixRowSize, int matrixColSize) { 36 |    spin(matrix, 0, matrixRowSize - 1); 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Medium 42 | Total Accepted:121.1K 43 | Total Submissions:314.2K 44 | 45 | 46 | Companies Amazon Microsoft Apple 47 | Related Topics Array 48 | 49 | */ 50 | -------------------------------------------------------------------------------- /5. Longest Palindromic Substring.c: -------------------------------------------------------------------------------- 1 | /* 2 | 5. Longest Palindromic Substring 3 | 4 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 5 | 6 | Example: 7 | Input: "babad" 8 | 9 | Output: "bab" 10 | 11 | Note: "aba" is also a valid answer. 12 | 13 | 14 | 15 | Example: 16 | Input: "cbbd" 17 | 18 | Output: "bb" 19 | */ 20 | 21 | char* longestPalindrome(char* s) { 22 | int sz; 23 | int i, j, k, l; 24 | int where = 0, len = 0; 25 | 26 | if (!s || !*s) return s; 27 | 28 | sz = strlen(s); 29 | 30 | for (i = 0, j = 0, k = 0; len < (sz - k) * 2; i = k, j = k) { 31 | while (j + 1 < sz && s[j] == s[j + 1]) { 32 | j ++; // skip all repeating characters 33 | } 34 | k = j + 1; // where to start next try 35 | while (i > 0 && j + 1 < sz && s[i - 1] == s[j + 1]) { 36 | i --; // expand dual direction 37 | j ++; 38 | } 39 | l = j - i + 1; // what we have fond so far 40 | if (len < l) { 41 | len = l; 42 | where = i; 43 | } 44 | } 45 | s = s + where; 46 | s[len] = 0; 47 | return s; 48 | } 49 | 50 | 51 | /* 52 | Difficulty:Medium 53 | Total Accepted:222.3K 54 | Total Submissions:883.5K 55 | 56 | 57 | Companies Amazon Microsoft Bloomberg 58 | Related Topics String 59 | Similar Questions 60 | 61 | 62 | Shortest Palindrome 63 | 64 | Palindrome Permutation 65 | 66 | Palindrome Pairs 67 | 68 | Longest Palindromic Subsequence 69 | 70 | Palindromic Substrings 71 | */ 72 | -------------------------------------------------------------------------------- /50. Pow(x, n).c: -------------------------------------------------------------------------------- 1 | /* 2 | 50. Pow(x, n) 3 | 4 | Implement pow(x, n). 5 | */ 6 | 7 | double powx(double x, int n) { 8 |    double k; 9 |    if (n == 0) return 1; 10 |    k = powx(x * x, n / 2); 11 |    if (n % 2) k = k * x; 12 |    return k; 13 | } 14 | double myPow(double x, int n) { 15 |    if (n < 0) { x = 1 / x; n = 0 - n; } 16 |    return powx(x, n); 17 | } 18 | 19 | 20 | /* 21 | Difficulty:Medium 22 | Total Accepted:161.2K 23 | Total Submissions:612.2K 24 | 25 | 26 | Companies LinkedIn Google Bloomberg Facebook 27 | Related Topics Binary Search Math 28 | Similar Questions 29 | 30 | 31 | Sqrt(x) 32 | 33 | Super Pow 34 | */ 35 | -------------------------------------------------------------------------------- /53. Maximum Subarray.c: -------------------------------------------------------------------------------- 1 | /* 2 | 53. Maximum Subarray 3 | 4 | Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 5 | 6 | 7 | For example, given the array [-2,1,-3,4,-1,2,1,-5,4], 8 | the contiguous subarray [4,-1,2,1] has the largest sum = 6. 9 | 10 | 11 | click to show more practice. 12 | 13 | More practice: 14 | 15 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 16 | */ 17 | 18 | int maxSubArray(int* nums, int numsSize) { 19 | int i, s, m = 0; 20 | m = s = nums[0]; 21 | for (i = 1; i < numsSize; i ++) { 22 | //printf("s: %d, m: %d\n", s, m); 23 | if (s > 0) s += nums[i]; 24 | else s = nums[i]; 25 | if (m < s) m = s; 26 | } 27 | //printf("s: %d, m: %d\n", s, m); 28 | return m; 29 | } 30 | 31 | 32 | /* 33 | Difficulty:Easy 34 | Total Accepted:216.1K 35 | Total Submissions:546K 36 | 37 | 38 | Companies LinkedIn Bloomberg Microsoft 39 | Related Topics Array Dynamic Programming Divide and Conquer 40 | Similar Questions 41 | 42 | 43 | Best Time to Buy and Sell Stock 44 | 45 | Maximum Product Subarray 46 | */ 47 | -------------------------------------------------------------------------------- /543. Diameter of Binary Tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | 543. Diameter of Binary Tree 3 | 4 | Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 5 | 6 | 7 | 8 | Example: 9 | Given a binary tree 10 | 1 11 | / \ 12 | 2 3 13 | / \ 14 | 4 5 15 | 16 | 17 | 18 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 19 | 20 | 21 | Note: 22 | The length of path between two nodes is represented by the number of edges between them. 23 | */ 24 | 25 | /** 26 | * Definition for a binary tree node. 27 | * struct TreeNode { 28 | *     int val; 29 | *     struct TreeNode *left; 30 | *     struct TreeNode *right; 31 | * }; 32 | */ 33 | int depth(struct TreeNode *node, int *m) { 34 |    int l, r; 35 |    if (!node) return 0; 36 |    l = depth(node->left,  m); 37 |    r = depth(node->right, m); 38 |    if (*m < l + r) *m = l + r; 39 |    if (r < l) r = l; 40 |    return r + 1; 41 | } 42 | int diameterOfBinaryTree(struct TreeNode* root) { 43 |    int m = 0; 44 |    depth(root,  &m); 45 |    return m; 46 | } 47 | 48 | 49 | /* 50 | Difficulty:Easy 51 | Total Accepted:23.7K 52 | Total Submissions:54.4K 53 | 54 | 55 | Companies Google Facebook 56 | Related Topics Tree 57 | 58 | */ 59 | -------------------------------------------------------------------------------- /554. Brick Wall.c: -------------------------------------------------------------------------------- 1 | /* 2 | 554. Brick Wall 3 | 4 | There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks. 5 | 6 | 7 | The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right. 8 | 9 | 10 | If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks. 11 | 12 | You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. 13 | 14 | Example: 15 | Input: 16 | [[1,2,2,1], 17 | [3,1,2], 18 | [1,3,2], 19 | [2,4], 20 | [3,1,2], 21 | [1,3,1,1]] 22 | Output: 2 23 | Explanation: 24 | 25 | 26 | 27 | 28 | Note: 29 | 30 | The width sum of bricks in different rows are the same and won't exceed INT_MAX. 31 | The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000. 32 | */ 33 | 34 | int leastBricks(int** wall, int wallRowSize, int *wallColSizes) { 35 |    // in the example, all edges are aligned at: 36 |    /* 1.3.5 37 |       ..34. 38 |       1..4. 39 |       .2... 40 |       ..34. 41 |       1..45 42 |    */ 43 |    // the most are at 4 44 |    return 4; 45 | } 46 | 47 | 48 | /* 49 | Difficulty:Medium 50 | Total Accepted:10.3K 51 | Total Submissions:23K 52 | 53 | 54 | Companies Facebook 55 | Related Topics Hash Table 56 | 57 | */ 58 | -------------------------------------------------------------------------------- /560. Subarray Sum Equals K.c: -------------------------------------------------------------------------------- 1 | /* 2 | 560. Subarray Sum Equals K 3 | 4 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 5 | 6 | Example 1: 7 | Input:nums = [1,1,1], k = 2 8 | Output: 2 9 | 10 | 11 | 12 | Note: 13 | 14 | The length of the array is in range [1, 20,000]. 15 | The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 16 | */ 17 | 18 | typedef struct e_s { 19 | int s; 20 | int c; 21 | struct e_s *next; 22 | } e_t; 23 | 24 | #define HF 1021 25 | #define HC(S) (((S) % HF) + HF) 26 | 27 | typedef struct { 28 | e_t *e[HF * 2]; 29 | e_t buff[20000]; 30 | int n; 31 | } ht_t; 32 | 33 | e_t *lookup(ht_t *ht, int s) { 34 | e_t *e = ht->e[HC(s)]; 35 | while (e && e->s != s) e = e->next; 36 | return e; 37 | } 38 | void insert(ht_t *ht, int s) { 39 | e_t *e = lookup(ht, s); 40 | if (e) e->c ++; 41 | else { 42 | e = &ht->buff[ht->n ++]; 43 | e->s = s; 44 | e->c = 1; 45 | e->next = ht->e[HC(s)]; 46 | ht->e[HC(s)] = e; 47 | } 48 | } 49 | int count(ht_t *ht, int s) { 50 | e_t *e = lookup(ht, s); 51 | if (e) return e->c; 52 | return 0; 53 | } 54 | int subarraySum(int* nums, int numsSize, int k){ 55 | int i, s, r, n; 56 | ht_t ht = { 0 }; 57 | 58 | n = 0; 59 | s = 0; 60 | 61 | insert(&ht, s); 62 | 63 | for (i = 0; i < numsSize; i ++) { 64 | s += nums[i]; 65 | 66 | n += count(&ht, s - k); 67 | 68 | insert(&ht, s); 69 | } 70 | 71 | return n; 72 | } 73 | 74 | 75 | /* 76 | Difficulty:Medium 77 | 78 | 79 | */ 80 | -------------------------------------------------------------------------------- /567. Permutation in String.c: -------------------------------------------------------------------------------- 1 | /* 2 | 567. Permutation in String 3 | 4 | Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. 5 | 6 | Example 1: 7 | Input:s1 = "ab" s2 = "eidbaooo" 8 | Output:True 9 | Explanation: s2 contains one permutation of s1 ("ba"). 10 | 11 | 12 | 13 | Example 2: 14 | Input:s1= "ab" s2 = "eidboaoo" 15 | Output: False 16 | 17 | 18 | 19 | Note: 20 | 21 | The input strings only contain lower case letters. 22 | The length of both given strings is in range [1, 10,000]. 23 | */ 24 | 25 | bool checkInclusion(char* s1, char* s2) { 26 |    int cnt[26] = { 0 }; 27 |    int total = 0; 28 |    int i, j; 29 |    char c, k; 30 |     31 |    while (c = *(s1 ++)) { 32 |        c -= 'a'; 33 |        cnt[c] ++; 34 |        total ++; 35 |   } 36 | ​ 37 |    i = j = 0; 38 |    while (c = s2[j ++]) { 39 |        c -= 'a'; 40 |        if (cnt[c] > 0) total --; 41 |        if (total == 0) return true;  // where i is the start index, j - i is the length 42 |        cnt[c] --; 43 |        while (cnt[c] < 0) { 44 |            k = s2[i ++]; 45 |            k -= 'a'; 46 |            cnt[k] ++; 47 |            if (cnt[k] > 0) total ++; 48 |       } 49 |   } 50 |     51 |    return false; 52 | } 53 | 54 | 55 | /* 56 | Difficulty:Medium 57 | Total Accepted:9.5K 58 | Total Submissions:26.1K 59 | 60 | 61 | Companies Microsoft 62 | Related Topics Two Pointers 63 | Similar Questions 64 | 65 | 66 | Minimum Window Substring 67 | 68 | Find All Anagrams in a String 69 | */ 70 | -------------------------------------------------------------------------------- /572. Subtree of Another Tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | 572. Subtree of Another Tree 3 | 4 | Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. 5 | 6 | 7 | Example 1: 8 | 9 | Given tree s: 10 | 3 11 | / \ 12 | 4 5 13 | / \ 14 | 1 2 15 | 16 | Given tree t: 17 | 4 18 | / \ 19 | 1 2 20 | 21 | Return true, because t has the same structure and node values with a subtree of s. 22 | 23 | 24 | Example 2: 25 | 26 | Given tree s: 27 | 3 28 | / \ 29 | 4 5 30 | / \ 31 | 1 2 32 | / 33 | 0 34 | 35 | Given tree t: 36 | 4 37 | / \ 38 | 1 2 39 | 40 | Return false. 41 | */ 42 | 43 | /** 44 | * Definition for a binary tree node. 45 | * struct TreeNode { 46 | *     int val; 47 | *     struct TreeNode *left; 48 | *     struct TreeNode *right; 49 | * }; 50 | */ 51 | bool equal(struct TreeNode *node, struct TreeNode *t) { 52 |    if (!node && !t) return true; 53 |    if (!node || !t || node->val != t->val) return false; 54 |    return equal(node->left, t->left) && equal(node->right, t->right); 55 | } 56 | bool isSubtree(struct TreeNode* s, struct TreeNode* t) { 57 |    if (equal(s, t) || 58 |       (s && isSubtree(s->left, t)) || 59 |       (s && isSubtree(s->right, t))) return true; 60 |    return false; 61 | } 62 | 63 | 64 | /* 65 | Difficulty:Easy 66 | Total Accepted:17.6K 67 | Total Submissions:43.3K 68 | 69 | 70 | Companies Facebook eBay 71 | Related Topics Tree 72 | Similar Questions 73 | 74 | 75 | Count Univalue Subtrees 76 | 77 | Most Frequent Subtree Sum 78 | */ 79 | -------------------------------------------------------------------------------- /6. ZigZag Conversion.c: -------------------------------------------------------------------------------- 1 | /* 2 | 6. ZigZag Conversion 3 | 4 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 5 | P A H N 6 | A P L S I I G 7 | Y I R 8 | 9 | 10 | And then read line by line: "PAHNAPLSIIGYIR" 11 | 12 | 13 | Write the code that will take a string and make this conversion given a number of rows: 14 | 15 | string convert(string text, int nRows); 16 | 17 | convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 18 | */ 19 | 20 | char* convert(char* s, int numRows) { 21 | int len; 22 | int i, j, k = 0; 23 | char *p; 24 | int step, up; 25 | 26 | if (!s || !*s || numRows == 1) return s; 27 | 28 | len = strlen(s); 29 | p = malloc((len + 1) * sizeof(char)); 30 | //assert(p); 31 | 32 | step = (numRows - 1) * 2; // max span 33 | 34 | for (i = 0; i < numRows; i ++) { 35 | j = i; // first letter of each row 36 | up = 1; 37 | while (j < len) { 38 | p[k ++] = s[j]; 39 | if (i == 0 || i == numRows - 1) { 40 | j += step; // full span 41 | } else if (up) { 42 | j += step - i * 2; // full span - offset 43 | up = 0; 44 | } else { 45 | j += i * 2; // offset 46 | up = 1; 47 | } 48 | } 49 | } 50 | p[k] = 0; 51 | return p; 52 | } 53 | 54 | 55 | /* 56 | Difficulty:Medium 57 | Total Accepted:163.3K 58 | Total Submissions:610.5K 59 | 60 | 61 | Related Topics String 62 | 63 | */ 64 | -------------------------------------------------------------------------------- /62. Unique Paths.c: -------------------------------------------------------------------------------- 1 | /* 2 | 62. Unique Paths 3 | 4 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 5 | 6 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 7 | 8 | How many possible unique paths are there? 9 | 10 | 11 | 12 | Above is a 3 x 7 grid. How many possible unique paths are there? 13 | 14 | 15 | Note: m and n will be at most 100. 16 | */ 17 | 18 | int uniquePaths(int m, int n) { 19 | int path[100][100]; 20 | int i, j; 21 | 22 | if (!m || !n) return 0; 23 | 24 | for (i = 0; i < m; i ++) { 25 | for (j = 0; j < n; j ++) { 26 | if (i == 0 || j == 0) { 27 | path[i][j] = 1; 28 | } else { 29 | path[i][j] = path[i][j - 1] + path[i - 1][j]; 30 | } 31 | } 32 | } 33 | return path[m - 1][n - 1]; 34 | } 35 | 36 | 37 | /* 38 | Difficulty:Medium 39 | Total Accepted:147.3K 40 | Total Submissions:358.4K 41 | 42 | 43 | Companies Bloomberg 44 | Related Topics Array Dynamic Programming 45 | Similar Questions 46 | 47 | 48 | Unique Paths II 49 | 50 | Minimum Path Sum 51 | 52 | Dungeon Game 53 | */ 54 | -------------------------------------------------------------------------------- /621. Task Scheduler.c: -------------------------------------------------------------------------------- 1 | /* 2 | 621. Task Scheduler 3 | 4 | Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. 5 | 6 | However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. 7 | 8 | You need to return the least number of intervals the CPU will take to finish all the given tasks. 9 | 10 | Example 1: 11 | Input: tasks = ['A','A','A','B','B','B'], n = 2 12 | Output: 8 13 | Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. 14 | 15 | 16 | 17 | Note: 18 | 19 | The number of tasks is in the range [1, 10000]. 20 | The integer n is in the range [0, 100]. 21 | */ 22 | 23 | int cmp(const void *a, const void *b) { 24 |    return *(int *)a < *(int *)b ?  1 : 25 |           *(int *)a > *(int *)b ? -1 : 0; 26 | } 27 | int leastInterval(char* tasks, int tasksSize, int n) { 28 |    int c[26] = { 0 }; 29 |    int i, k; 30 |    for (i = 0; i < tasksSize; i ++) { 31 |        c[tasks[i] - 'A'] ++; 32 |   } 33 |    qsort(c, 26, sizeof(int), cmp); 34 |    i = 1; 35 |    while (i < 26 && c[i] == c[0]) { 36 |        i ++; 37 |   } 38 |    k = (c[0] - 1) * (n + 1) + i; 39 |    return tasksSize > k ? tasksSize : k; 40 | } 41 | 42 | 43 | /* 44 | Difficulty:Medium 45 | Total Accepted:11.8K 46 | Total Submissions:27.8K 47 | 48 | 49 | Companies Facebook 50 | Related Topics Array Greedy Queue 51 | Similar Questions 52 | 53 | 54 | Rearrange String k Distance Apart 55 | */ 56 | -------------------------------------------------------------------------------- /647. Palindromic Substrings.c: -------------------------------------------------------------------------------- 1 | /* 2 | 647. Palindromic Substrings 3 | 4 | Given a string, your task is to count how many palindromic substrings in this string. 5 | 6 | The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. 7 | 8 | Example 1: 9 | 10 | Input: "abc" 11 | Output: 3 12 | Explanation: Three palindromic strings: "a", "b", "c". 13 | 14 | 15 |   16 | 17 | Example 2: 18 | 19 | Input: "aaa" 20 | Output: 6 21 | Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". 22 | 23 | 24 |   25 | 26 | Note: 27 | 28 | 29 | The input string length won't exceed 1000. 30 | */ 31 | 32 | #define IDX(I, J, L) ((I) * (L) + J) 33 | ​ 34 | int countSubstrings(char* s) { 35 |    int i, j, l; 36 |    int *mem, p, ans; 37 |     38 |    if (!s || !*s) return 0; 39 |     40 |    l = strlen(s); 41 |    mem = calloc(l * l, sizeof(int)); 42 |    //assert(mem); 43 |     44 |    ans = 0; 45 |    for (i = 0; i < l; i ++) { 46 |        for (j = 0; j <= i; j ++) { 47 |            if (s[i] == s[j] && 48 |               (i - j <= 1 || mem[IDX(i - 1, j + 1, l)] != 0)) { 49 |                p = 1; 50 |                ans ++; 51 |           } else { 52 |                p = 0; 53 |           } 54 |            mem[IDX(i, j, l)] = p; 55 |       } 56 |   } 57 | 58 |    free(mem); 59 |     60 |    return ans; 61 | } 62 | 63 | 64 | /* 65 | Difficulty:Medium 66 | 67 | 68 | */ 69 | -------------------------------------------------------------------------------- /65. Valid Number.c: -------------------------------------------------------------------------------- 1 | /* 2 | 65. Valid Number 3 | 4 | Validate if a given string is numeric. 5 | 6 | 7 | Some examples: 8 | "0" => true 9 | " 0.1 " => true 10 | "abc" => false 11 | "1 a" => false 12 | "2e10" => true 13 | 14 | 15 | Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. 16 | 17 | 18 | 19 | Update (2015-02-10): 20 | The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. 21 | */ 22 | 23 | bool isNumber(char* s) { 24 |    int n, m; 25 |     26 |    // skip leading spaces 27 |    while (*s == ' ') s ++; 28 |     29 |    n = m = 0; 30 |     31 |    // skip the sign of the number 32 |    if (*s == '+' || *s == '-') s ++; 33 |     34 |    while (*s >= '0' && *s <= '9') { 35 |        n ++; 36 |        s ++; 37 |   } 38 |     39 |    if (*s == '.') { 40 |        s ++; 41 |        while (*s >= '0' && *s <= '9') { 42 |            m ++; 43 |            s ++; 44 |       } 45 |        if (!n && !m) return false; 46 |   } else if (!n) { 47 |        return false; 48 |   } 49 |     50 |    if (*s == 'e' || *s == 'E') { 51 |        s ++; 52 |        if (*s == '+' || *s == '-') s ++; 53 |        n = 0; 54 |        while (*s >= '0' && *s <= '9') { 55 |            n ++; 56 |            s ++; 57 |       } 58 |        if (!n) return false; 59 |   } 60 |     61 |    while (*s == ' ') s ++; 62 |     63 |    return *s == 0 ? true : false; 64 | } 65 | 66 | 67 | /* 68 | Difficulty:Hard 69 | Total Accepted:70K 70 | Total Submissions:550K 71 | 72 | 73 | Companies LinkedIn 74 | Related Topics Math String 75 | Similar Questions 76 | 77 | 78 | String to Integer (atoi) 79 | */ 80 | -------------------------------------------------------------------------------- /66. Plus One.c: -------------------------------------------------------------------------------- 1 | /* 2 | 66. Plus One 3 | 4 | Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. 5 | 6 | You may assume the integer do not contain any leading zero, except the number 0 itself. 7 | 8 | The digits are stored such that the most significant digit is at the head of the list. 9 | */ 10 | 11 | /** 12 | * Return an array of size *returnSize. 13 | * Note: The returned array must be malloced, assume caller calls free(). 14 | */ 15 | int* plusOne(int* digits, int digitsSize, int* returnSize) { 16 |    int s = 1; 17 |    int i; 18 |    int *p; 19 |     20 |    p = malloc((digitsSize + 1) * sizeof(int)); 21 |    if (!p) return NULL; 22 |     23 |    i = digitsSize - 1; 24 |    while (i >= 0) { 25 |        //if (s) { 26 |            p[i] = (digits[i] + s) % 10; 27 |            s = (digits[i] + s) / 10; 28 |        //} else { 29 |        //   p[i] = digits[i]; 30 |        //} 31 |        i --; 32 |   } 33 |    if (s) { 34 |        memcpy(&p[1], &p[0], digitsSize * sizeof(int)); 35 |        //i = digitsSize - 1; 36 |        //while (i >= 0) { 37 |        //   p[i + 1] = p[i]; 38 |        //   i --; 39 |        //} 40 |        p[0] = 1; 41 |        *returnSize = digitsSize + 1; 42 |   } else { 43 |        *returnSize = digitsSize; 44 |   } 45 |    return p; 46 | } 47 | 48 | 49 | /* 50 | Difficulty:Easy 51 | Total Accepted:181.2K 52 | Total Submissions:469.5K 53 | 54 | 55 | Companies Google 56 | Related Topics Array Math 57 | Similar Questions 58 | 59 | 60 | Multiply Strings 61 | 62 | Add Binary 63 | 64 | Plus One Linked List 65 | */ 66 | -------------------------------------------------------------------------------- /69. Sqrt(x).c: -------------------------------------------------------------------------------- 1 | /* 2 | 69. Sqrt(x) 3 | 4 | Implement int sqrt(int x). 5 | 6 | Compute and return the square root of x. 7 | */ 8 | 9 | int mySqrt(int x) { 10 | #if 1 11 |    int left, right, mid, k; 12 |    if (!x) return 0; 13 |    left = 1; 14 |    right = (x < 46340 * 2) ? (x + 1) / 2 : 46340; 15 |    while (left <= right) { 16 |        mid = left + (right - left) / 2; 17 |        //printf("mid: %d\n", mid); 18 |        k = mid * mid; 19 |        if (k == x) return mid; 20 |        if (k < x) left = mid + 1; 21 |        else       right = mid - 1; 22 |   } 23 |    return right; 24 | #else 25 |    unsigned long long r = (x + 1) / 2; 26 |    if (r > 46340) r = 46340; 27 |    while (r * r > x) { 28 |        //printf("r: %lld\n", r); 29 |        r = (r + x / r) / 2; 30 |   } 31 | ​ 32 |    return r; 33 | #endif 34 | } 35 | 36 | 37 | /* 38 | Difficulty:Easy 39 | Total Accepted:166.8K 40 | Total Submissions:599.6K 41 | 42 | 43 | Companies Bloomberg Apple Facebook 44 | Related Topics Binary Search Math 45 | Similar Questions 46 | 47 | 48 | Pow(x, n) 49 | 50 | Valid Perfect Square 51 | */ 52 | -------------------------------------------------------------------------------- /693. Binary Number with Alternating Bits.c: -------------------------------------------------------------------------------- 1 | /* 2 | 693. Binary Number with Alternating Bits 3 | 4 | Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. 5 | 6 | Example 1: 7 | Input: 5 8 | Output: True 9 | Explanation: 10 | The binary representation of 5 is: 101 11 | 12 | 13 | 14 | Example 2: 15 | Input: 7 16 | Output: False 17 | Explanation: 18 | The binary representation of 7 is: 111. 19 | 20 | 21 | 22 | Example 3: 23 | Input: 11 24 | Output: False 25 | Explanation: 26 | The binary representation of 11 is: 1011. 27 | 28 | 29 | 30 | Example 4: 31 | Input: 10 32 | Output: True 33 | Explanation: 34 | The binary representation of 10 is: 1010. 35 | */ 36 | 37 | unsigned int first_bit_on(unsigned int k, unsigned int sz) { 38 | unsigned int m = sz / 2; 39 | if (k == 1) return 1; 40 | 41 | if ((k >> m) == 0) { 42 | return first_bit_on(k, m); 43 | } 44 | 45 | return m + first_bit_on(k >> m, m); 46 | } 47 | 48 | bool hasAlternatingBits(int n){ 49 | unsigned int k = n; 50 | unsigned int b = first_bit_on(n, 32); 51 | //printf("%d\n", b); 52 | return (k ^ (k >> 1)) == ((unsigned int)1 << b) - 1 ? true : false; 53 | } 54 | 55 | 56 | /* 57 | Difficulty:Easy 58 | 59 | 60 | */ 61 | -------------------------------------------------------------------------------- /7. Reverse Integer.c: -------------------------------------------------------------------------------- 1 | /* 2 | 7. Reverse Integer 3 | 4 | Reverse digits of an integer. 5 | 6 | 7 | Example1: x = 123, return 321 8 | Example2: x = -123, return -321 9 | 10 | 11 | click to show spoilers. 12 | 13 | Have you thought about this? 14 | 15 | Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 16 | 17 | If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 18 | 19 | Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases? 20 | 21 | For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 22 | 23 | 24 | 25 | 26 | 27 | Note: 28 | The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. 29 | */ 30 | 31 | int reverse(int x) { 32 | int d, k = 0; 33 | // 2147483647 34 | //-2147483648 35 | while (x) { 36 | d = x % 10; 37 | if ((x > 0 && k > (0x7fffffff - d) / 10) || 38 | (x < 0 && k < ((signed)0x80000000 - d) / 10)) { 39 | return 0; // overflow 40 | } 41 | k = k * 10 + d; 42 | x = x / 10; 43 | } 44 | return k; //(int)k == k ? (int)k : 0; 45 | } 46 | 47 | 48 | /* 49 | Difficulty:Easy 50 | Total Accepted:275.6K 51 | Total Submissions:1.1M 52 | 53 | 54 | Companies Bloomberg Apple 55 | Related Topics Math 56 | Similar Questions 57 | 58 | 59 | String to Integer (atoi) 60 | */ 61 | -------------------------------------------------------------------------------- /70. Climbing Stairs.c: -------------------------------------------------------------------------------- 1 | /* 2 | 70. Climbing Stairs 3 | 4 | You are climbing a stair case. It takes n steps to reach to the top. 5 | 6 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 7 | 8 | 9 | Note: Given n will be a positive integer. 10 | */ 11 | 12 | int climbStairs(int n) { 13 |    int p, pp, k, i; 14 |     15 |    if (n == 1) return 1; 16 |    if (n == 2) return 2; 17 |     18 |    p = 2; 19 |    pp = 1; 20 |     21 |    for (i = 3; i <= n; i++) { 22 |        k = p + pp; 23 |        pp = p; 24 |        p  = k; 25 |   } 26 |     27 |    return p; 28 | } 29 | 30 | 31 | /* 32 | Difficulty:Easy 33 | Total Accepted:186.3K 34 | Total Submissions:465.8K 35 | 36 | 37 | Companies Adobe Apple 38 | Related Topics Dynamic Programming 39 | 40 | */ 41 | -------------------------------------------------------------------------------- /72. Edit Distance.c: -------------------------------------------------------------------------------- 1 | /* 2 | 72. Edit Distance 3 | 4 | Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) 5 | 6 | 7 | 8 | You have the following 3 operations permitted on a word: 9 | 10 | 11 | 12 | a) Insert a character 13 | b) Delete a character 14 | c) Replace a character 15 | */ 16 | 17 | int minDistance(char* word1, char* word2) { 18 |    int rowsz, colsz, row, col, *dp, k; 19 |     20 |    rowsz = strlen(word1); 21 |    colsz = strlen(word2); 22 |     23 |    dp = malloc((rowsz + 1) * (colsz + 1) * sizeof(int)); 24 |    //assert(dp); 25 | #define IDX(ROW, COL) ((ROW + 1) * (colsz + 1) + (COL + 1)) 26 |     27 |    dp[0] = 0; 28 |    for (row = 0; row < rowsz; row ++) { 29 |        dp[IDX(row, -1)] = row + 1; 30 |   } 31 |    for (col = 0; col < colsz; col ++) { 32 |        dp[IDX(-1, col)] = col + 1; 33 |   } 34 |     35 |    for (row = 0; row < rowsz; row ++) { 36 |        for (col = 0; col < colsz; col ++) { 37 |            k = dp[IDX(row - 1, col - 1)]; 38 |            if (word1[row] != word2[col]) { 39 |                k = k < dp[IDX(row - 1, col)] ? k : dp[IDX(row - 1, col)]; 40 |                k = k < dp[IDX(row, col - 1)] ? k : dp[IDX(row, col - 1)]; 41 |                k += 1; 42 |           } 43 |            dp[IDX(row, col)] = k; 44 |       } 45 |   } 46 |     47 |    k = dp[IDX(rowsz - 1, colsz - 1)]; 48 |    free(dp); 49 |     50 |    return k; 51 | } 52 | 53 | 54 | /* 55 | Difficulty:Hard 56 | Total Accepted:92.4K 57 | Total Submissions:291.9K 58 | 59 | 60 | Related Topics Dynamic Programming String 61 | Similar Questions One Edit Distance Delete Operation for Two Strings 62 | 63 | */ 64 | -------------------------------------------------------------------------------- /74. Search a 2D Matrix.c: -------------------------------------------------------------------------------- 1 | /* 2 | 74. Search a 2D Matrix 3 | 4 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 5 | 6 | 7 | 8 | Integers in each row are sorted from left to right. 9 | The first integer of each row is greater than the last integer of the previous row. 10 | 11 | 12 | 13 | 14 | For example, 15 | 16 | Consider the following matrix: 17 | 18 | [ 19 | [1, 3, 5, 7], 20 | [10, 11, 16, 20], 21 | [23, 30, 34, 50] 22 | ] 23 | 24 | 25 | Given target = 3, return true. 26 | */ 27 | 28 | bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { 29 |    int s, x, z, y, mr, mc; 30 |    int a, b, c; 31 |    s = 0; x = matrixRowSize - 1; 32 |    while (s <= x) { 33 |        mr = s + (x - s) / 2; 34 |        a = matrix[mr][0]; 35 |        b = matrix[mr][matrixColSize - 1]; 36 |        if (target >= a && target <= b) { 37 |            z = 0; y = matrixColSize - 1; 38 |            while (z <= y) { 39 |                mc = z + (y - z) / 2; 40 |                c = matrix[mr][mc]; 41 |                if (target == c) return true; 42 |                if (target <  c) y = mc - 1; 43 |                else             z = mc + 1; 44 |           } 45 |            return false; 46 |       } 47 |        if (target < a) x = mr - 1; 48 |        else            s = mr + 1; 49 |   } 50 |     51 |    return false; 52 | } 53 | 54 | 55 | /* 56 | Difficulty:Medium 57 | Total Accepted:129.6K 58 | Total Submissions:369.7K 59 | 60 | 61 | Related Topics Array Binary Search 62 | Similar Questions Search a 2D Matrix II 63 | 64 | */ 65 | -------------------------------------------------------------------------------- /762. Prime Number of Set Bits in Binary Representation.c: -------------------------------------------------------------------------------- 1 | /* 2 | 762. Prime Number of Set Bits in Binary Representation 3 | 4 | Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation. 5 | 6 | (Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.) 7 | 8 | 9 | Example 1:Input: L = 6, R = 10 10 | Output: 4 11 | Explanation: 12 | 6 -> 110 (2 set bits, 2 is prime) 13 | 7 -> 111 (3 set bits, 3 is prime) 14 | 9 -> 1001 (2 set bits , 2 is prime) 15 | 10->1010 (2 set bits , 2 is prime) 16 | 17 | 18 | Example 2:Input: L = 10, R = 15 19 | Output: 5 20 | Explanation: 21 | 10 -> 1010 (2 set bits, 2 is prime) 22 | 11 -> 1011 (3 set bits, 3 is prime) 23 | 12 -> 1100 (2 set bits, 2 is prime) 24 | 13 -> 1101 (3 set bits, 3 is prime) 25 | 14 -> 1110 (3 set bits, 3 is prime) 26 | 15 -> 1111 (4 set bits, 4 is not prime) 27 | 28 | 29 | Note: 30 | L, R will be integers L <= R in the range [1, 10^6]. 31 | R - L will be at most 10000. 32 | */ 33 | 34 | int numOfBits(n) { 35 |    int k = 0; 36 |    while (n) { 37 |        k ++; 38 |        n = n & (n - 1); 39 |   } 40 |    return k; 41 | } 42 | ​ 43 | int countPrimeSetBits(int L, int R){ 44 |    int k = (1 << 2) | 45 |           (1 << 3) | 46 |           (1 << 5) | 47 |           (1 << 7) | 48 |           (1 << 11) | 49 |           (1 << 13) | 50 |           (1 << 17) | 51 |           (1 << 19); 52 |    int ans = 0; 53 |    while (L <= R) { 54 |        if ((k >> numOfBits(L)) & 1) ans ++; 55 |        /* equals to: 56 |        if (numOfBits(L) is 2 or 3 or 5 or 7 ... 57 |        */ 58 | 59 |   } 60 |    return ans; 61 | } 62 | 63 | 64 | /* 65 | Difficulty:Easy 66 | 67 | 68 | */ 69 | -------------------------------------------------------------------------------- /767. Reorganize String.c: -------------------------------------------------------------------------------- 1 | /* 2 | 767. Reorganize String 3 | 4 | Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. 5 | 6 | If possible, output any possible result.  If not possible, return the empty string. 7 | 8 | Example 1: 9 | 10 | Input: S = "aab" 11 | Output: "aba" 12 | 13 | 14 | Example 2: 15 | 16 | Input: S = "aaab" 17 | Output: "" 18 | 19 | 20 | Note: 21 | 22 | 23 | S will consist of lowercase letters and have length in range [1, 500]. 24 | */ 25 | 26 | typedef struct { 27 | char c; 28 | int n; 29 | } e_t; 30 | int cmp(const void *a, const void *b) { 31 | e_t *p1 = a; 32 | e_t *p2 = b; 33 | return (p1->n < p2->n) ? 1 : 34 | (p1->n > p2->n) ? -1 : 0; 35 | } 36 | char * reorganizeString(char * S){ 37 | e_t e[27] = { 0 }, x; 38 | char c, *p, *buff; 39 | int i, t, sz; 40 | 41 | buff = malloc(501); 42 | //assert(buff); 43 | buff[0] = 0; 44 | 45 | while (c = *(S ++)) { 46 | i = c - 'a'; 47 | e[i].c = c; 48 | e[i].n ++; 49 | } 50 | 51 | qsort(&e, 26, sizeof(e_t), cmp); 52 | 53 | for (i = 25; i >= 0; i --) if (e[i].n > 0) break; 54 | 55 | sz = i + 1; 56 | 57 | p = buff; 58 | *p = 0; 59 | 60 | while (e[0].n > 0) { 61 | *p = e[0].c; 62 | p ++; 63 | e[0].n --; 64 | 65 | if (e[1].n > 0) { 66 | *p = e[1].c; 67 | p ++; 68 | e[1].n --; 69 | } else if (e[0].n > 0) { 70 | buff[0] = 0; 71 | break; 72 | } 73 | 74 | qsort(&e, sz, sizeof(e_t), cmp); // use heap to optimze 75 | } 76 | 77 | *p = 0; 78 | return buff; 79 | }     80 | 81 | 82 | /* 83 | Difficulty:Medium 84 | 85 | 86 | */ 87 | -------------------------------------------------------------------------------- /777. Swap Adjacent in LR String.c: -------------------------------------------------------------------------------- 1 | /* 2 | 777. Swap Adjacent in LR String 3 | 4 | In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other. 5 | 6 | Example: 7 | 8 | Input: start = "RXXLRXRXL", end = "XRLXXRRLX" 9 | Output: True 10 | Explanation: 11 | We can transform start to end following these steps: 12 | RXXLRXRXL -> 13 | XRXLRXRXL -> 14 | XRLXRXRXL -> 15 | XRLXXRRXL -> 16 | XRLXXRRLX 17 | 18 | 19 | Note: 20 | 21 | 22 | 1 <= len(start) = len(end) <= 10000. 23 | Both start and end will only consist of characters in {'L', 'R', 'X'}. 24 | */ 25 | 26 | // L can move ahead of X, R can move after X. 27 | // skip X from start and end: 28 | // if both are L, and this L in start does not appear earlier than the L in end, this is ok since L can move ahead; 29 | // if both are R, and this R in start does not appear later than the R in end, this is ok since R can move afterwards. 30 | bool canTransform(char * start, char * end){ 31 |    int i, j; 32 |     33 |    i = j = 0; 34 |    while (start[i] && end[i]) { 35 |        while (start[i] == 'X') i ++; 36 |        while (end[j] == 'X') j ++; 37 |         38 |        if (start[i] == 0 && end[j] == 0) return true; 39 |        if (start[i] == 0 || end[j] == 0) return false; 40 |         41 |        if (start[i] != end[j] || 42 |           (start[i] == 'L' && i < j) || 43 |           (start[i] == 'R' && i > j)) return false; 44 | 45 |        i ++; j ++; 46 |   } 47 |     48 |    return true; 49 | } 50 | ​ 51 | ​ 52 | 53 | 54 | /* 55 | Difficulty:Medium 56 | 57 | 58 | */ 59 | -------------------------------------------------------------------------------- /780. Reaching Points.c: -------------------------------------------------------------------------------- 1 | /* 2 | 780. Reaching Points 3 | 4 | A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y). 5 | 6 | Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False. 7 | 8 | Examples: 9 | Input: sx = 1, sy = 1, tx = 3, ty = 5 10 | Output: True 11 | Explanation: 12 | One series of moves that transforms the starting point to the target is: 13 | (1, 1) -> (1, 2) 14 | (1, 2) -> (3, 2) 15 | (3, 2) -> (3, 5) 16 | 17 | Input: sx = 1, sy = 1, tx = 2, ty = 2 18 | Output: False 19 | 20 | Input: sx = 1, sy = 1, tx = 1, ty = 1 21 | Output: True 22 | 23 | 24 | 25 | Note: 26 | 27 | 28 | sx, sy, tx, ty will all be integers in the range [1, 10^9]. 29 | */ 30 | 31 | 32 | bool reachingPoints(int sx, int sy, int tx, int ty){ 33 | #if 0 34 | if (sx == tx && sy == ty) return true; 35 | if (sx > tx || sy > ty) return false; 36 | return (reachingPoints(sx, sx + sy, tx, ty) || 37 | reachingPoints(sx + sy, sy, tx, ty)); 38 | #else 39 | while (tx >= sx && ty >= sy) { 40 | if (tx == sx && ty == sy) return true; 41 | if (tx > ty) { 42 | tx -= ty; 43 | } else { 44 | ty -= tx; 45 | } 46 | } 47 | return false; 48 | #endif 49 | } 50 | 51 | 52 | /* 53 | Difficulty:Hard 54 | 55 | 56 | */ 57 | -------------------------------------------------------------------------------- /80. Remove Duplicates from Sorted Array II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 80. Remove Duplicates from Sorted Array II 3 | 4 | Follow up for "Remove Duplicates": 5 | What if duplicates are allowed at most twice? 6 | 7 | 8 | For example, 9 | Given sorted array nums = [1,1,1,2,2,3], 10 | 11 | 12 | Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. 13 | */ 14 | 15 | int removeDuplicates(int* nums, int numsSize) { 16 |    int i, j; 17 |     18 |    if (numsSize < 3) return numsSize; 19 |     20 |    for (i = 2, j = 2; j < numsSize; j ++) { 21 |        if (nums[j] != nums[i - 2]) { 22 |            nums[i] = nums[j]; 23 |            i ++; 24 |       } 25 |   } 26 |     27 |    return i; 28 | } 29 | 30 | 31 | /* 32 | Difficulty:Medium 33 | Total Accepted:122.8K 34 | Total Submissions:341.5K 35 | 36 | 37 | Companies Facebook 38 | Related Topics Array Two Pointers 39 | 40 | */ 41 | -------------------------------------------------------------------------------- /81. Search in Rotated Sorted Array II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 81. Search in Rotated Sorted Array II 3 | 4 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | 6 | (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). 7 | 8 | You are given a target value to search. If found in the array return true, otherwise return false. 9 | 10 | Example 1: 11 | 12 | Input: nums = [2,5,6,0,0,1,2], target = 0 13 | Output: true 14 | 15 | 16 | Example 2: 17 | 18 | Input: nums = [2,5,6,0,0,1,2], target = 3 19 | Output: false 20 | 21 | Follow up: 22 | 23 | 24 | This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. 25 | Would this affect the run-time complexity? How and why? 26 | */ 27 | 28 | bool search(int* nums, int numsSize, int target){ 29 | int start, end, mid; 30 | start = 0; end = numsSize - 1; 31 | while (start <= end) { 32 | mid = start + (end - start) / 2; 33 | if (nums[mid] == target) return true; 34 | if (nums[start] == nums[mid]) { 35 | start ++; 36 | } else if (nums[start] < nums[mid]) { // first half are sorted 37 | if (target > nums[mid] || target < nums[start]) { 38 | start = mid + 1; 39 | } else { 40 | end = mid - 1; 41 | } 42 | } else { // second half are sorted 43 | if (target < nums[mid] || target > nums[end]) { 44 | end = mid - 1; 45 | } else { 46 | start = mid + 1; 47 | } 48 | } 49 | } 50 | return false; 51 | } 52 | 53 | 54 | /* 55 | Difficulty:Medium 56 | 57 | 58 | */ 59 | -------------------------------------------------------------------------------- /82. Remove Duplicates from Sorted List II.c: -------------------------------------------------------------------------------- 1 | /* 2 | 82. Remove Duplicates from Sorted List II 3 | 4 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 5 | 6 | 7 | For example, 8 | Given 1->2->3->3->4->4->5, return 1->2->5. 9 | Given 1->1->1->2->3, return 2->3. 10 | */ 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * struct ListNode { 15 | *     int val; 16 | *     struct ListNode *next; 17 | * }; 18 | */ 19 | struct ListNode* deleteDuplicates(struct ListNode* head) { 20 |    struct ListNode *a, *b, *prev = NULL; 21 |    a = head; 22 |    head = NULL; 23 |    while (a) { 24 |        b = a->next; 25 |        if (!b || a->val != b->val) { 26 |            if (!prev) head = a; 27 |            else prev->next = a; 28 |            prev = a; 29 |       } else { 30 |            do {  // skip all duplicated ones 31 |                b = b->next; 32 |           } while (b && b->val == a->val); 33 |       } 34 |        a = b; 35 |   } 36 |    if (prev) prev->next = NULL; 37 |    return head; 38 | } 39 | 40 | 41 | /* 42 | Difficulty:Medium 43 | Total Accepted:113.1K 44 | Total Submissions:384.1K 45 | 46 | 47 | Related Topics Linked List 48 | 49 | */ 50 | -------------------------------------------------------------------------------- /83. Remove Duplicates from Sorted List.c: -------------------------------------------------------------------------------- 1 | /* 2 | 83. Remove Duplicates from Sorted List 3 | 4 | Given a sorted linked list, delete all duplicates such that each element appear only once. 5 | 6 | 7 | For example, 8 | Given 1->1->2, return 1->2. 9 | Given 1->1->2->3->3, return 1->2->3. 10 | */ 11 | 12 | /** 13 | * Definition for singly-linked list. 14 | * struct ListNode { 15 | *     int val; 16 | *     struct ListNode *next; 17 | * }; 18 | */ 19 | struct ListNode* deleteDuplicates(struct ListNode* head) { 20 |    struct ListNode *prev, *p; 21 |     22 |    if (!head) return NULL; 23 |     24 |    prev = head; 25 |    p = prev->next; 26 |     27 |    while (p) { 28 |        if (prev->val != p->val) { 29 |            prev->next = p; 30 |            prev = p; 31 |       } 32 |        p = p->next; 33 |   } 34 |    prev->next = NULL; 35 |     36 |    return head; 37 | } 38 | 39 | 40 | /* 41 | Difficulty:Easy 42 | Total Accepted:191.9K 43 | Total Submissions:481.8K 44 | 45 | 46 | Related Topics Linked List 47 | 48 | */ 49 | -------------------------------------------------------------------------------- /88. Merge Sorted Array.c: -------------------------------------------------------------------------------- 1 | /* 2 | 88. Merge Sorted Array 3 | 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | 7 | Note: 8 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. 9 | */ 10 | 11 | void merge(int* nums1, int m, int* nums2, int n) { 12 |    int k = m + n - 1; 13 |    m --; 14 |    n --; 15 |    while (n >= 0) { 16 |        while (m >= 0 && nums1[m] > nums2[n]) { 17 |            nums1[k--] = nums1[m--]; 18 |       } 19 |        nums1[k--] = nums2[n--]; 20 |   } 21 | } 22 | 23 | 24 | /* 25 | Difficulty:Easy 26 | Total Accepted:175.3K 27 | Total Submissions:547.7K 28 | 29 | 30 | Companies Microsoft Bloomberg Facebook 31 | Related Topics Array Two Pointers 32 | Similar Questions 33 | 34 | 35 | Merge Two Sorted Lists 36 | */ 37 | -------------------------------------------------------------------------------- /89. Gray Code.c: -------------------------------------------------------------------------------- 1 | /* 2 | 89. Gray Code 3 | 4 | The gray code is a binary numeral system where two successive values differ in only one bit. 5 | 6 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 7 | 8 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 9 | 00 - 0 10 | 01 - 1 11 | 11 - 3 12 | 10 - 2 13 | 14 | 15 | Note: 16 | For a given n, a gray code sequence is not uniquely defined. 17 | 18 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 19 | 20 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. 21 | */ 22 | 23 | /** 24 | * Return an array of size *returnSize. 25 | * Note: The returned array must be malloced, assume caller calls free(). 26 | */ 27 | int* grayCode(int n, int* returnSize) { 28 |    int i, j; 29 |    int *p, psz, pn; 30 |     31 |    psz = 1 << n; 32 |    p = malloc(psz * sizeof(int)); 33 |    //assert(p); 34 |     35 |    pn = 0; 36 |    p[pn ++] = 0; 37 |    for (i = 0; i < n; i ++) { 38 |        for (j = pn - 1; j >= 0; j --) { 39 |            p[pn ++] = p[j] | (1 << i); 40 |       } 41 |   } 42 |     43 |    *returnSize = pn; 44 |     45 |    return p; 46 | } 47 | 48 | 49 | /* 50 | Difficulty:Medium 51 | Total Accepted:92.4K 52 | Total Submissions:224.8K 53 | 54 | 55 | Companies Amazon 56 | Related Topics Backtracking 57 | 58 | */ 59 | -------------------------------------------------------------------------------- /9. Palindrome Number.c: -------------------------------------------------------------------------------- 1 | /* 2 | 9. Palindrome Number 3 | 4 | Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 5 | 6 | Example 1: 7 | 8 | Input: 121 9 | Output: true 10 | 11 | 12 | Example 2: 13 | 14 | Input: -121 15 | Output: false 16 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 17 | 18 | 19 | Example 3: 20 | 21 | Input: 10 22 | Output: false 23 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 24 | 25 | 26 | Follow up: 27 | 28 | Coud you solve it without converting the integer to a string? 29 | */ 30 | 31 | bool isPalindrome(int x) { 32 | int n, d, k = 0; 33 | 34 | if (x < 0) return false; 35 | 36 | n = x; 37 | while (n) { 38 | d = n % 10; 39 | if (k > (0x7fffffff - d) / 10) return false; // overflow 40 | k = k * 10 + d; 41 | n = n / 10; 42 | } 43 | 44 | return (k == x); 45 | } 46 | 47 | 48 | /* 49 | Difficulty:Easy 50 | 51 | 52 | */ 53 | -------------------------------------------------------------------------------- /91. Decode Ways.c: -------------------------------------------------------------------------------- 1 | /* 2 | 91. Decode Ways 3 | 4 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 5 | 6 | 7 | 'A' -> 1 8 | 'B' -> 2 9 | ... 10 | 'Z' -> 26 11 | 12 | 13 | 14 | Given an encoded message containing digits, determine the total number of ways to decode it. 15 | 16 | 17 | 18 | For example, 19 | Given encoded message "12", 20 | it could be decoded as "AB" (1 2) or "L" (12). 21 | 22 | 23 | 24 | The number of ways decoding "12" is 2. 25 | */ 26 | 27 | int numDecodings(char* s) { 28 | int a, b, c; 29 | char p, t; 30 | 31 | /* a b c 32 | 2267312 33 | 0 1 34 | */ 35 | a = 0; 36 | b = 1; 37 | c = 0; 38 | p = 'x'; // anything other than '1' or '2' 39 | 40 | while (t = *s ++) { 41 | if (t == '0') { 42 | if (p != '1' && p != '2') { 43 | return 0; 44 | } 45 | c = a; 46 | } else { 47 | c = b; 48 | if (p == '1' || (p == '2' && t <= '6')) { 49 | c += a; 50 | } 51 | } 52 | a = b; 53 | b = c; 54 | p = t; 55 | } 56 | 57 | return c; 58 | } 59 | 60 | 61 | /* 62 | Difficulty:Medium 63 | Total Accepted:128.3K 64 | Total Submissions:654.3K 65 | 66 | 67 | Companies Microsoft Uber Facebook 68 | Related Topics Dynamic Programming String 69 | Similar Questions 70 | 71 | 72 | Decode Ways II 73 | */ 74 | -------------------------------------------------------------------------------- /96. Unique Binary Search Trees.c: -------------------------------------------------------------------------------- 1 | /* 2 | 96. Unique Binary Search Trees 3 | 4 | Given n, how many structurally unique BST's (binary search trees) that store values 1...n? 5 | 6 | 7 | For example, 8 | Given n = 3, there are a total of 5 unique BST's. 9 | 10 | 1 3 3 2 1 11 | \ / / / \ \ 12 | 3 2 1 1 3 2 13 | / / \ \ 14 | 2 1 2 3 15 | */ 16 | 17 | int numTrees(int n) { 18 |    int *dp; 19 |    int i, j; 20 |     21 |    dp = calloc((n + 1), sizeof(int)); 22 |    //assert(dp); 23 |     24 |    dp[0] = dp[1] = 1; 25 |     26 |    for (i = 2; i <= n; i ++) { 27 |        for (j = 1; j <= i; j ++) { 28 |            dp[i] += dp[j - 1] * dp[i - j]; 29 |       } 30 |   } 31 |     32 |    i = dp[n]; 33 |    free(dp); 34 |     35 |    return i; 36 | } 37 | 38 | 39 | /* 40 | Difficulty:Medium 41 | Total Accepted:125.7K 42 | Total Submissions:307K 43 | 44 | 45 | Companies Snapchat 46 | Related Topics Tree Dynamic Programming 47 | Similar Questions 48 | 49 | 50 | Unique Binary Search Trees II 51 | */ 52 | -------------------------------------------------------------------------------- /98. Validate Binary Search Tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | 98. Validate Binary Search Tree 3 | 4 | Given a binary tree, determine if it is a valid binary search tree (BST). 5 | 6 | 7 | 8 | Assume a BST is defined as follows: 9 | 10 | The left subtree of a node contains only nodes with keys less than the node's key. 11 | The right subtree of a node contains only nodes with keys greater than the node's key. 12 | Both the left and right subtrees must also be binary search trees. 13 | 14 | 15 | 16 | Example 1: 17 | 2 18 | / \ 19 | 1 3 20 | 21 | Binary tree [2,1,3], return true. 22 | 23 | 24 | Example 2: 25 | 1 26 | / \ 27 | 2 3 28 | 29 | Binary tree [1,2,3], return false. 30 | */ 31 | 32 | /** 33 | * Definition for a binary tree node. 34 | * struct TreeNode { 35 | *     int val; 36 | *     struct TreeNode *left; 37 | *     struct TreeNode *right; 38 | * }; 39 | */ 40 | bool isValid(struct TreeNode* p, struct TreeNode** prev) { 41 |    if (!p) return true; 42 |    if (!isValid(p->left, prev)) return false; 43 |    if (*prev && p->val <= (*prev)->val) return false; 44 |    *prev = p; 45 |    return (isValid(p->right, prev)); 46 | } 47 | bool isValidBST(struct TreeNode* root) { 48 |    struct TreeNode *prev = NULL; 49 |    return isValid(root, &prev); 50 | } 51 | 52 | 53 | /* 54 | Difficulty:Medium 55 | Total Accepted:174.5K 56 | Total Submissions:749K 57 | 58 | 59 | Companies Amazon Microsoft Bloomberg Facebook 60 | Related Topics Tree Depth-first Search 61 | Similar Questions 62 | 63 | 64 | Binary Tree Inorder Traversal 65 | 66 | Find Mode in Binary Search Tree 67 | */ 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # My leetcode solutions in C. 2 | 3 | Many beat 100% c submissions. 4 | 5 | Free for use, no liability, no license is required. 6 | 7 | Author: vli02us@gmail.com 8 | 10/12/2022 9 | --------------------------------------------------------------------------------