├── ExcelSheetColumnNumber.java ├── ExcelSheetColumnTitle.java ├── Happy-Number.java ├── MajorityElement.java ├── MergeTwoSortedLists.java ├── README.md ├── RemoveLinkedListElements.java ├── ReverseBits.java ├── SingleNumber.java ├── addBinary.java ├── addTwoNumbers.java ├── deleteDuplicates.java ├── generate.java ├── hasCycle.java ├── hasPathSum.java ├── inorderTraversal.java ├── isBalanced.java ├── isPalindrome.java ├── isSameTree.java ├── isSymmetric.java ├── isValid.java ├── lengthOfLastWord.java ├── lengthOfLongestSubString.java ├── longestCommonPrefix.java ├── maxDepth.java ├── maxProfit.java ├── minDepth.java ├── mySqrt.java ├── plusOne.java ├── removeDuplicates.java ├── removeElement.java ├── romanToInteger.java ├── searchInsertPosition.java ├── sortedArrayToBST.java ├── twoSum.java └── validPalindrome.java /ExcelSheetColumnNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | /** 4 | * Class LeetCode.java 5 | * A class with solutions to leet code problems 6 | */ 7 | public class LeetCode 8 | { 9 | /** 10 | * https://leetcode.com/problems/excel-sheet-column-number/ 11 | * Easy 12 | * problem 171 Excel Sheet Column Number 13 | * Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number. 14 | * Math, String 15 | */ 16 | public int titleToNumber(String columnTitle) 17 | { 18 | int result = 0; 19 | for(char c : columnTitle.toCharArray()) 20 | { 21 | int d = c - 'A' + 1; 22 | result = result*26 + d; 23 | } 24 | return result; 25 | }// end of method titleToNumber 26 | }// end of class LeetCode 27 | -------------------------------------------------------------------------------- /ExcelSheetColumnTitle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Class LeetCode.java 3 | * A class with solutions to leet code problems 4 | */ 5 | public class LeetCode 6 | { 7 | /** 8 | * https://leetcode.com/problems/excel-sheet-column-title/ 9 | * Easy 10 | * problem 168 Excel Sheet column Title 11 | * Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. 12 | * Math, String 13 | */ 14 | public String convertToTitle(int columnNumber) 15 | { 16 | String str = ""; 17 | 18 | while(columnNumber > 0) 19 | { 20 | columnNumber--; 21 | str = (char) (columnNumber%26 + 'A') + str; 22 | columnNumber = columnNumber / 26; 23 | } 24 | return str; 25 | }// end of method convertToTitle 26 | }// end of class LeetCode 27 | -------------------------------------------------------------------------------- /Happy-Number.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Class LeetCode.java 4 | * A class with solutions to leet code problems 5 | */ 6 | public class LeetCode 7 | { 8 | /** 9 | * https://leetcode.com/problems/happy-number/ 10 | * Easy 11 | * problem 202 Happy Number 12 | * Write an algorithm to determine if a number n is happy. 13 | * A happy number is a number defined by the following process: 14 | * Starting with any positive integer, replace the number by the sum of the squares of its digits. 15 | * Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. 16 | * Those numbers for which this process ends in 1 are happy. 17 | * Return true if n is a happy number, and false if not. 18 | * Hash Table, Math, Two Pointers 19 | */ 20 | public boolean isHappy(int n) 21 | { 22 | Set numbersSet = new HashSet<>(); 23 | 24 | while( n != 1) 25 | { 26 | int sum = 0; 27 | int curr = n; 28 | 29 | while( curr != 0) 30 | { 31 | int rem = curr % 10; 32 | sum += rem * rem; 33 | curr /= 10; 34 | } 35 | 36 | if(numbersSet.contains(sum)) 37 | { 38 | return false; 39 | } 40 | n = sum; 41 | numbersSet.add(n); 42 | } 43 | return true; 44 | } 45 | )// end of class LeetCode 46 | -------------------------------------------------------------------------------- /MajorityElement.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | /** 4 | * Class LeetCode.java 5 | * A class with solutions to leet code problems 6 | */ 7 | public class LeetCode 8 | { 9 | /** 10 | * https://leetcode.com/problems/majority-element/ 11 | * Easy 12 | * problem 169 Majority Element 13 | * Given an array nums of size n, return the majority element. 14 | * The majority element is the element that appears more than ⌊n / 2⌋ times. 15 | * You may assume that the majority element always exists in the array. 16 | * Array, Hash Table Divide and Conquer, Sorting, Counting 17 | */ 18 | public int majorityElement(int[] nums) 19 | { 20 | HashMap map = new HashMap<>(); 21 | for(int num : nums) 22 | { 23 | if(!map.containsKey(num)) 24 | { 25 | map.put(num, 1); 26 | } 27 | else 28 | { 29 | map.put(num, map.get(num) + 1); 30 | } 31 | if(map.get(num) > nums.length / 2) 32 | { 33 | return num; 34 | } 35 | } 36 | return 0; 37 | } 38 | }// end of class LeetCode 39 | 40 | -------------------------------------------------------------------------------- /MergeTwoSortedLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Class LeetCode.java 3 | * A class with solutions to leet code problems 4 | */ 5 | public class LeetCode 6 | { 7 | /** 8 | * https://leetcode.com/problems/merge-two-sorted-lists/ 9 | * problem 21 Merge Two Sorted Lists 10 | * Easy 11 | * You are given the heads of two sorted linked lists list1 and list2. 12 | * Merge the two lists in a one sorted list. 13 | * The list should be made by splicing together the nodes of 14 | * the first two lists. 15 | * Return the head of the merged linked list. 16 | */ 17 | public ListNode mergeTwoLists(ListNode list1, ListNode list2) 18 | { 19 | ListNode tempNode = new ListNode(0); 20 | ListNode currNode = tempNode; 21 | 22 | while(list1 != null && list2 != null) 23 | { 24 | if(list1.val < list2.val) 25 | { 26 | currNode.next = list1; 27 | list1 = list1.next; 28 | } 29 | else 30 | { 31 | currNode.next = list2; 32 | list2 = list2.next; 33 | } 34 | } 35 | if(list1 != null) 36 | { 37 | currNode.next = list1; 38 | list1 = list1.next; 39 | } 40 | else if(list2 != null) 41 | { 42 | currNode.next = list2; 43 | list2 = list2.next; 44 | } 45 | return tempNode.next; 46 | }// end of method mergeTwoLists 47 | }// end of class LeetCode 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

🤔 LeetCode 🤔

2 | 3 | 4 | 5 | Designed for tracking my progress and saving the code of the exercises I solved in leet code in the java language 6 | 7 |

Leetcode Stats Card

8 | 9 | ![IGotASolutionIdiocracyGIF](https://user-images.githubusercontent.com/91504420/213186619-cce73715-449b-491f-b533-3280037dda25.gif) 10 | 11 | 12 | -------------------------------------------------------------------------------- /RemoveLinkedListElements.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Class LeetCode.java 3 | * A class with solutions to leet code problems 4 | */ 5 | public class LeetCode 6 | { 7 | /** 8 | * https://leetcode.com/problems/remove-linked-list-elements/ 9 | * problem 203 Remove Linked List Elements 10 | * Easy 11 | * Given the head of a linked list and an integer val, remove all the nodes of the 12 | * linked list that has Node.val == val, and return the new head. 13 | * Linked List, Recursion 14 | */ 15 | public ListNode removeElements(ListNode head, int val) 16 | { 17 | while(head != null && head.val == val) 18 | { 19 | head = head.next; 20 | } 21 | ListNode curr_node = head; 22 | while(curr_node != null && curr_node. next != null) 23 | { 24 | if(curr_node.next.val == val) 25 | { 26 | curr_node.next = curr_node.next.next; 27 | } 28 | else 29 | { 30 | curr_node = curr_node.next; 31 | } 32 | } 33 | return head; 34 | }// end of method removeElements 35 | }// end of class LeetCode 36 | -------------------------------------------------------------------------------- /ReverseBits.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | /** 4 | * Class LeetCode.java 5 | * A class with solutions to leet code problems 6 | */ 7 | public class LeetCode 8 | { 9 | /** 10 | * https://leetcode.com/problems/reverse-bits/ 11 | * Easy 12 | * problem 190 Reverse Bits 13 | * Reverse bits of a given 32 bits unsigned integer. return its corresponding column number. 14 | * Divide and Conquer, Bit Manipulation 15 | */ 16 | // you need treat n as an unsigned value 17 | public int reverseBits(int n) 18 | { 19 | int result = 0; 20 | for(int i = 0; i < 32; i++) 21 | { 22 | result <<=1; 23 | result += n%2; 24 | n>>>=1; 25 | } 26 | return result; 27 | }// end of method reverseBits 28 | }// end of class LeetCode 29 | -------------------------------------------------------------------------------- /SingleNumber.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/single-number/ 5 | * problem 136 Single Number 6 | * Easy 7 | * Given a non-empty array of integers nums, every element appears 8 | * twice except for one. Find that single one. 9 | * You must implement a solution with a linear runtime complexity 10 | * and use only constant extra space. 11 | * Array, Bit Manipulation 12 | */ 13 | public int singleNumber(int[] nums) 14 | { 15 | int result = 0; 16 | for(int i = 0; i < nums.length; i++) 17 | { 18 | result ^= nums[i]; 19 | } 20 | return result; 21 | }// end of method singleNumber 22 | }// end of class LeetCode 23 | -------------------------------------------------------------------------------- /addBinary.java: -------------------------------------------------------------------------------- 1 | ** 2 | * Class LeetCode.java 3 | * A class with solutions to leet code problems 4 | */ 5 | public class LeetCode 6 | { 7 | /** 8 | * https://leetcode.com/problems/add-binary/ 9 | * problem 67 Add Binary 10 | * Easy 11 | * Given two binary strings a and b, return their sum as a binary string. 12 | * bit manipulation, math, string 13 | */ 14 | public String addBinary(String a, String b) 15 | { 16 | StringBuilder sb = new StringBuilder(); 17 | int i = a.length() - 1; 18 | int j = b.length() - 1; 19 | int carry = 0; 20 | 21 | while(i >= 0 || j >= 0) 22 | { 23 | int sum = carry; 24 | if(i >= 0) 25 | { 26 | sum += a.charAt(i) - '0'; 27 | } 28 | if( j >= 0) 29 | { 30 | sum += b.charAt(j) - '0'; 31 | } 32 | sb.append(sum % 2); 33 | carry = sum / 2; 34 | 35 | i--; 36 | j--; 37 | } 38 | 39 | if(carry != '0') 40 | { 41 | sb.append(carry); 42 | } 43 | 44 | return sb.reverse().toString(); 45 | }// end of method addBinary 46 | }// end of class LeetCode 47 | 48 | -------------------------------------------------------------------------------- /addTwoNumbers.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.HashMap; 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Class LeetCode.java 7 | * A class with solutions to leet code problems 8 | */ 9 | public class LeetCode 10 | { 11 | /** 12 | * https://leetcode.com/problems/add-two-numbers/ 13 | * problem 2 Add Two Numbers 14 | * Definition for singly-linked list. 15 | * You are given two non-empty linked lists 16 | * representing two non-negative integers. 17 | * The digits are stored in reverse order, 18 | * and each of their nodes contains a single digit. 19 | * Add the two numbers and return the sum as a linked list. 20 | * public class ListNode 21 | * { 22 | * int val; 23 | * ListNode next; 24 | * ListNode() {} 25 | * ListNode(int val) { this.val = val; } 26 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 27 | * } 28 | */ 29 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) 30 | { 31 | ListNode dummyHead = new ListNode(0); 32 | ListNode l3 = dummyHead; 33 | 34 | int carry = 0; 35 | while(l1 != null || l2 != null) 36 | { 37 | int l1_val = (l1 != null) ? l1.val : 0; 38 | int l2_val = (l2 != null) ? l2.val : 0; 39 | 40 | int currSum = l1_val + l2_val + carry; 41 | carry = currSum / 10; 42 | int lastDigit = currSum % 10; 43 | 44 | ListNode newNode = new ListNode(lastDigit); 45 | l3.next = newNode; 46 | 47 | if(l1 != null) 48 | { 49 | l1 = l1.next; 50 | } 51 | 52 | if(l2 != null) 53 | { 54 | l2 = l2.next; 55 | } 56 | l3 = l3.next; 57 | } 58 | if( carry > 0) 59 | { 60 | ListNode newNode = new ListNode(carry); 61 | l3.next = newNode; 62 | l3 = l3.next; 63 | } 64 | return dummyHead.next; 65 | }// end of method addTwoNumbers 66 | 67 | 68 | 69 | 70 | 71 | } 72 | -------------------------------------------------------------------------------- /deleteDuplicates.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ 5 | * problem 83 Remove Duplicates from Sorted List 6 | * Easy 7 | *Given the head of a sorted linked list, delete all duplicates 8 | *such that each element appears only once. 9 | *Return the linked list sorted as well. 10 | */ 11 | public ListNode deleteDuplicates(ListNode head) 12 | { 13 | ListNode currentNode = head; 14 | 15 | while(currentNode != null && currentNode.next != null) 16 | { 17 | if(currentNode.next.val == currentNode.val) 18 | { 19 | currentNode.next = currentNode.next.next; 20 | } 21 | else 22 | { 23 | currentNode = currentNode.next; 24 | } 25 | } 26 | return head; 27 | }// end of method deleteDuplicates 28 | }// end of class LeetCode 29 | -------------------------------------------------------------------------------- /generate.java: -------------------------------------------------------------------------------- 1 | public class Leetcode 2 | { 3 | /** 4 | * https://leetcode.com/problems/pascals-triangle/ 5 | * problem 118 Pascal's Triangle 6 | * Easy 7 | * Given an integer numRows, return the first numRows of Pascal's triangle. 8 | * In Pascal's triangle, each number is the sum of the two numbers 9 | * directly above it as shown: 10 | * Array, Dynamic Programing 11 | */ 12 | public List> generate(int numRows) 13 | { 14 | List> triangleList = new ArrayList<>(); 15 | List first_row = new ArrayList<>(); 16 | first_row.add(1); 17 | triangleList.add(first_row); 18 | 19 | for(int i=1; i < numRows; i++) 20 | { 21 | List prev_row = triangleList.get(i -1); 22 | List currRow = new ArrayList<>(); 23 | 24 | currRow.add(1); 25 | for(int j = 1; j < i; j++) 26 | { 27 | currRow.add(prev_row.get(j - 1) + prev_row.get(j)); 28 | } 29 | currRow.add(1); 30 | triangleList.add(currRow); 31 | } 32 | return triangleList; 33 | }// end of method generate 34 | }// end of class LeetCode 35 | -------------------------------------------------------------------------------- /hasCycle.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/linked-list-cycle/ 5 | * problem 141 Linked List Cycle 6 | * Easy 7 | * Given head, the head of a linked list, determine if the linked list 8 | * has a cycle in it. There is a cycle in a linked list if there 9 | * is some node in the list that can be reached again by continuously 10 | * following the next pointer. Internally, pos is used to denote 11 | * the index of the node that tail's next pointer is connected to. 12 | * Note that pos is not passed as a parameter. Return true 13 | * if there is a cycle in the linked list. Otherwise, return false. 14 | * Hash Table, Linked List, Two Pointers 15 | */ 16 | public boolean hasCycle(ListNode head) 17 | { 18 | if(head == null) 19 | { 20 | return false; 21 | } 22 | ListNode slow = head; 23 | ListNode fast = head.next; 24 | 25 | while(slow != fast) 26 | { 27 | if(fast == null || fast.next == null ) 28 | { 29 | return false; 30 | } 31 | slow = slow.next; 32 | fast = fast.next.next; 33 | } 34 | return true; 35 | }// end of method hasCycle 36 | }// end of class LeetCode 37 | -------------------------------------------------------------------------------- /hasPathSum.java: -------------------------------------------------------------------------------- 1 | public Class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/path-sum/ 5 | * problem 112 Path Sum 6 | * Easy 7 | * Given the root of a binary tree and an integer targetSum, 8 | * return true if the tree has a root-to-leaf path such that 9 | * adding up all the values along the path equals targetSum. 10 | * A leaf is a node with no children. 11 | * Tree, Depth-First-Search, Breasth-First-Search, Binary tree 12 | */ 13 | public boolean hasPathSum(TreeNode root, int targetSum) 14 | { 15 | if (root == null) return false; 16 | if (root.val == targetSum && root.left == null && root.right == null) return true; 17 | return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val); 18 | }// end of method hasPathSum 19 | }// end of class LeetCode 20 | -------------------------------------------------------------------------------- /inorderTraversal.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/binary-tree-inorder-traversal/ 5 | * problem 94 Binary Tree Inorder Traversal 6 | * Easy 7 | * Given the root of a binary tree, return the 8 | * inorder traversal of its nodes' values. 9 | * Stack, Tree, Depth-First-Search, Binary-Tree 10 | */ 11 | public List inorderTraversal(TreeNode root) 12 | { 13 | Stack stack = new Stack(); 14 | List output_arr = new ArrayList(); 15 | if(root == null) 16 | { 17 | return output_arr; 18 | } 19 | TreeNode current = root; 20 | while(current != null || !stack.isEmpty()) 21 | { 22 | while(current != null) 23 | { 24 | stack.push(current); 25 | current = current.left; 26 | } 27 | current = stack.pop(); 28 | output_arr.add(current.val); 29 | current = current.right; 30 | } 31 | return output_arr; 32 | }// end of method inordertraversal 33 | }// end of class LeetCode 34 | -------------------------------------------------------------------------------- /isBalanced.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/balanced-binary-tree/ 5 | * problem 110 Balanced Binary Tree 6 | * Easy 7 | * Given a binary tree, determine if it is height-balanced 8 | * Tree, Depth-First-Search, Binary tree 9 | */ 10 | private int getHeight(TreeNode tree) 11 | { 12 | if(tree == null) 13 | { 14 | return 0; 15 | } 16 | int left = getHeight(tree.left); 17 | int right = getHeight(tree.right); 18 | int bf = Math.abs(left - right); 19 | if(bf > 1 || left == -1 || right == -1) 20 | { 21 | return -1; 22 | } 23 | return 1 + Math.max(left, right); 24 | }// end of method getHeight 25 | public boolean isBalanced(TreeNode root) 26 | { 27 | if(root == null) 28 | { 29 | return true; 30 | } 31 | return getHeight(root) != -1; 32 | }// end of method isBalanced 33 | }// end of class LeetCode 34 | -------------------------------------------------------------------------------- /isPalindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.HashMap; 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Class LeetCode.java 7 | * A class with solutions to leet code problems 8 | */ 9 | public class LeetCode 10 | { 11 | /** 12 | * https://leetcode.com/problems/palindrome-number/ 13 | * Easy 14 | * problem 9 Palindrome Number 15 | * Given an integer x, return true if x is a palindrome and false otherwise. 16 | * Math 17 | */ 18 | public boolean isPalindrome(int x) 19 | { 20 | int a, b = 0, c = x; 21 | if ( x == 0) 22 | { 23 | return true; 24 | } 25 | 26 | if( x < 0 || x % 10 == 0) 27 | { 28 | return false; 29 | } 30 | 31 | while(c > 0) 32 | { 33 | a = c % 10; 34 | b = b * 10 + a; 35 | c /= 10; 36 | } 37 | if(b == x) 38 | { 39 | return true; 40 | } 41 | else 42 | { 43 | return false; 44 | } 45 | }// end of method isPalindrome 46 | }// end of class LeetCode 47 | -------------------------------------------------------------------------------- /isSameTree.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/same-tree/ 5 | * problem 100 Same Tree 6 | * Easy 7 | * Given the roots of two binary trees p and q, write a function 8 | * to check if they are the same or not. Two binary trees are 9 | * considered the same if they are structurally identical, and the 10 | * nodes have the same value. 11 | * Tree, Depth-First-Search, Binary-Tree, Breadth-First-Search 12 | */ 13 | public boolean isSameTree(TreeNode p, TreeNode q) 14 | { 15 | if(p == null && q == null) 16 | { 17 | return true; 18 | } 19 | else if(p == null || q == null) 20 | { 21 | return false; 22 | } 23 | else if(p.val != q.val) 24 | { 25 | return false; 26 | } 27 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 28 | }// end of method isSameTree 29 | }// end of class LeetCode 30 | -------------------------------------------------------------------------------- /isSymmetric.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/symmetric-tree/ 5 | * problem 101 Symmetric Tree 6 | * Easy 7 | * Given the root of a binary tree, check whether it is a mirror of itself 8 | * (i.e., symmetric around its center). 9 | * Tree, Depth-First-Search, Binary-Tree, Breadth-First-Search 10 | */ 11 | public boolean isSymmetric(TreeNode root) 12 | { 13 | return isMirror(root, root); 14 | }// end of method isSymmetric 15 | public boolean isMirror(TreeNode tree1, TreeNode tree2) 16 | { 17 | if(tree1 == null && tree2 == null) 18 | { 19 | return true; 20 | } 21 | if(tree1 == null || tree2 == null) 22 | { 23 | return false; 24 | } 25 | return (tree1.val == tree2.val) && isMirror(tree1.left, tree2.right) && isMirror(tree1.right, tree2.left); 26 | }// end of method isMirror 27 | }// end of class LeetCode 28 | -------------------------------------------------------------------------------- /isValid.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.HashMap; 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Class LeetCode.java 7 | * A class with solutions to leet code problems 8 | */ 9 | public class LeetCode 10 | { 11 | /** 12 | * https://leetcode.com/problems/valid-parentheses/ 13 | * problem 20 Valid Parenthess 14 | * Easy 15 | * Given a string s containing just the characters 16 | * '(', ')', '{', '}', '[' and ']', determine if the input string 17 | * is valid. An input string is valid if: Open brackets must be closed 18 | * by the same type of brackets. Open brackets must be closed in the 19 | * correct order. Every close bracket has a corresponding open bracket 20 | * of the same type. 21 | * Stack, String 22 | */ 23 | public boolean isValid(String s) 24 | { 25 | if (s.length() % 2 != 0) 26 | { 27 | return false; 28 | } 29 | 30 | Stack stack = new Stack(); 31 | for(char c : s.toCharArray()) 32 | { 33 | if (c == '(' || c == '{' || c == '[') 34 | { 35 | stack.push(c); 36 | } 37 | else if( c == ')' && !stack.isEmpty() && stack.peek() == '(') 38 | { 39 | stack.pop(); 40 | } 41 | else if( c == '}' && !stack.isEmpty() && stack.peek() == '{') 42 | { 43 | stack.pop(); 44 | } 45 | else if( c == ']' && !stack.isEmpty() && stack.peek() == '[') 46 | { 47 | stack.pop(); 48 | } 49 | } 50 | return stack.isEmpty(); 51 | }// end of method isValid 52 | } 53 | -------------------------------------------------------------------------------- /lengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Class LeetCode.java 4 | * A class with solutions to leet code problems 5 | */ 6 | public class LeetCode 7 | { 8 | /** 9 | * https://leetcode.com/problems/length-of-last-word/description/ 10 | * problem 58 Length of Last Word 11 | * Easy 12 | * Given a string s consisting of words and spaces, 13 | * return the length of the last word in the string. 14 | * A word is a maximal substring consisting of non-space characters only. 15 | */ 16 | public int lengthOfLastWord(String s) 17 | { 18 | s = s.trim(); 19 | int lastIndex = s.lastIndexOf(' ') + 1; 20 | return s.length() - lastIndex; 21 | }// end of method lengthOfLastWord 22 | }// end of class LeetCode 23 | -------------------------------------------------------------------------------- /lengthOfLongestSubString.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.HashMap; 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Class LeetCode.java 7 | * A class with solutions to leet code problems 8 | */ 9 | public class LeetCode 10 | { 11 | /** 12 | * https://leetcode.com/problems/longest-substring-without-repeating-characters/ 13 | * Medium 14 | * problem 3 Longest Substring without repeating characters 15 | * Given a string s, find the length of the longest 16 | * substring without repeating characters. 17 | * sliding window 18 | */ 19 | public int lengthOfLongestSubstring(String s) 20 | { 21 | int aPointer = 0; 22 | int bPointer = 0; 23 | int max = 0; 24 | 25 | HashSet hashSet = new HashSet(); 26 | 27 | while( bPointer < s.length()) 28 | { 29 | if(!hashSet.contains(s.charAt(bPointer))) 30 | { 31 | hashSet.add(s.charAt(bPointer)); 32 | bPointer++; 33 | max = Math.max(hashSet.size(), max); 34 | } 35 | else 36 | { 37 | hashSet.remove(s.charAt(aPointer)); 38 | aPointer++; 39 | } 40 | } 41 | return max; 42 | }// end of method lengthOfLongestSubstring 43 | }// end of class LeetCode 44 | -------------------------------------------------------------------------------- /longestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.HashMap; 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Class LeetCode.java 7 | * A class with solutions to leet code problems 8 | */ 9 | public class LeetCode 10 | { 11 | /** 12 | * https://leetcode.com/problems/longest-common-prefix/ 13 | * Easy 14 | * problem 14 Longest common prefix 15 | * Write a function to find the longest common prefix string 16 | * amongst an array of strings. 17 | * If there is no common prefix, return an empty string 18 | * String 19 | */ 20 | public String longestCommonPrefix(String[] strs) 21 | { 22 | if (strs.length == 0) 23 | { 24 | return ""; 25 | } 26 | String prefix = strs[0]; 27 | for(int i = 1; i < strs.length; i++) 28 | { 29 | while(strs[i].indexOf(prefix) != 0) 30 | { 31 | prefix = prefix.substring(0, prefix.length() - 1); 32 | } 33 | } 34 | return prefix; 35 | }// end of method longestCommonPrefix 36 | }// end of class LeetCode 37 | -------------------------------------------------------------------------------- /maxDepth.java: -------------------------------------------------------------------------------- 1 | public class Leetcode 2 | { 3 | /** 4 | * https://leetcode.com/problems/maximum-depth-of-binary-tree/ 5 | * problem 104 Maximum Depth of Binary Tree 6 | * Easy 7 | * Given the root of a binary tree, return its maximum depth. 8 | * A binary tree's maximum depth is the number of 9 | * nodes along the longest path from the root node down to 10 | * the farthest leaf node. 11 | * Tree, Depth-First-Search, Binary-Tree, Breadth-First-Search 12 | */ 13 | public int maxDepth(TreeNode root) 14 | { 15 | if(root == null) 16 | { 17 | return 0; 18 | } 19 | int left = maxDepth(root.left); 20 | int right = maxDepth(root.right); 21 | return Math.max(left, right) + 1; 22 | }// end of method maxDepth 23 | }// end of class LeetCode 24 | -------------------------------------------------------------------------------- /maxProfit.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 5 | * problem 121 Best Time to Buy and Sell Stock 6 | * Easy 7 | * You are given an array prices where prices[i] is the price 8 | * of a given stock on the ith day. You want to maximize 9 | * your profit by choosing a single day to buy one stock and 10 | * choosing a different day in the future to sell that stock. 11 | * Return the maximum profit you can achieve from this transaction. 12 | * If you cannot achieve any profit, return 0. 13 | * Array, Dynamic Programing 14 | */ 15 | public int maxProfit(int[] prices) 16 | { 17 | int min_val = Integer.MAX_VALUE; 18 | int max_profit = 0; 19 | for(int i = 0; i < prices.length; i++) 20 | { 21 | if(prices[i] < min_val) 22 | { 23 | min_val = prices[i]; 24 | } 25 | else if(prices[i] - min_val > max_profit) 26 | { 27 | max_profit = prices[i] - min_val; 28 | } 29 | } 30 | return max_profit; 31 | }// end of method maxProfit 32 | }// end of class LeetCode 33 | -------------------------------------------------------------------------------- /minDepth.java: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/problems/minimum-depth-of-binary-tree/ 3 | * problem 111 Minimum Depth of Binary Tree 4 | * Easy 5 | * Given a binary tree, find its minimum depth. 6 | * The minimum depth is the number of nodes along the shortest 7 | * path from the root node down to the nearest leaf node. 8 | * Tree, Depth-First-Search, Breasth-First-Search, Binary tree 9 | */ 10 | public int minDepth(TreeNode root) 11 | { 12 | if(root == null) 13 | { 14 | return 0; 15 | } 16 | if(root.left == null) 17 | { 18 | return 1 + minDepth(root.right); 19 | } 20 | else if (root.right == null) 21 | { 22 | return 1 + minDepth(root.left); 23 | } 24 | return 1 + Math.min(minDepth(root.left), minDepth(root.right)); 25 | }// end of method minDepth 26 | -------------------------------------------------------------------------------- /mySqrt.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Class LeetCode.java 3 | * A class with solutions to leet code problems 4 | */ 5 | public class LeetCode 6 | { 7 | /** 8 | * https://leetcode.com/problems/plus-one/ 9 | * problem 69 Sqrt(x) 10 | * Easy 11 | *Given a non-negative integer x, return the square root of x 12 | *rounded down to the nearest integer. 13 | *The returned integer should be non-negative as well. 14 | *You must not use any built-in exponent function or operator. 15 | *Binary Search 16 | */ 17 | public int mySqrt(int x) 18 | { 19 | if ( x < 2) 20 | { 21 | return x; 22 | } 23 | 24 | long num; 25 | int mid; 26 | int left = 2; 27 | int right = x/2; 28 | 29 | while(left <= right) 30 | { 31 | mid = (left + right) / 2; 32 | num = (long) mid * mid; 33 | if(num > x) 34 | { 35 | right = mid - 1; 36 | } 37 | else if(num < x) 38 | { 39 | left = mid + 1; 40 | } 41 | else 42 | { 43 | return mid; 44 | } 45 | } 46 | return right; 47 | }// end of method mySqrt 48 | }// end of class LeetCode 49 | -------------------------------------------------------------------------------- /plusOne.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Class LeetCode.java 4 | * A class with solutions to leet code problems 5 | */ 6 | public class LeetCode 7 | { 8 | /** 9 | * https://leetcode.com/problems/plus-one/ 10 | * problem 66 Plus One 11 | * Easy 12 | * You are given a large integer represented as an integer array digits, 13 | * where each digits[i] is the ith digit of the integer. 14 | * The digits are ordered from most significant to least significant 15 | * in left-to-right order. The large integer does not contain any 16 | * leading 0's. Increment the large integer by one and return 17 | * the resulting array of digits. 18 | */ 19 | public int[] plusOne(int[] digits) 20 | { 21 | int n = digits.length; 22 | for(int i = n - 1; i >= 0; i--) 23 | { 24 | if(digits[i] < 9) 25 | { 26 | digits[i]++; 27 | return digits; 28 | } 29 | digits[i] = 0; 30 | } 31 | int[] number = new int[n + 1]; 32 | number[0] = 1; 33 | return number; 34 | }// end of method plusOne 35 | }// end of class LeetCode 36 | 37 | -------------------------------------------------------------------------------- /removeDuplicates.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Class LeetCode.java 3 | * A class with solutions to leet code problems 4 | */ 5 | public class LeetCode 6 | { 7 | /** 8 | * https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 9 | * problem 26 Remove Duplicates from Sorted Array 10 | * Easy 11 | * Given an integer array nums sorted in non-decreasing order, remove 12 | * the duplicates in-place such that each unique element appears 13 | * only once. The relative order of the elements should be kept the same. 14 | * Since it is impossible to change the length of the array in some 15 | * languages, you must instead have the result be placed in the first 16 | * part of the array nums. More formally, if there are k elements after 17 | * removing the duplicates, then the first k elements of nums should hold the 18 | * final result. It does not matter what you leave beyond the first k elements. 19 | * Return k after placing the final result in the first k slots of nums. 20 | * Do not allocate extra space for another array. You must do this 21 | * by modifying the input array in-place with O(1) extra memory. 22 | */ 23 | public int removeDuplicates(int[] nums) 24 | { 25 | int slowPointer = 0; 26 | 27 | for(int j = 1; j < nums.length; j++) 28 | { 29 | if(nums[slowPointer] != nums[j]) 30 | { 31 | slowPointer += 1; 32 | nums[slowPointer] = nums[j]; 33 | } 34 | } 35 | return slowPointer + 1; 36 | }// end of method removeDuplicates 37 | }// end of class LeetCode 38 | -------------------------------------------------------------------------------- /removeElement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Class LeetCode.java 3 | * A class with solutions to leet code problems 4 | */ 5 | public class LeetCode 6 | { 7 | /** 8 | * https://leetcode.com/problems/remove-element/description/ 9 | * problem 27 Remove Element 10 | * Easy 11 | * Given an integer array nums and an integer val, 12 | * remove all occurrences of val in nums in-place. 13 | * The relative order of the elements may be changed. 14 | * 15 | * Since it is impossible to change the length of the array 16 | * in some languages, you must instead have the result be placed 17 | * in the first part of the array nums. More formally, if there 18 | * are k elements after removing the duplicates, then the first k 19 | * elements of nums should hold the final result. 20 | * 21 | * It does not matter what you leave beyond the first k elements. 22 | * Return k after placing the final result in the first k slots of nums. 23 | * Do not allocate extra space for another array. 24 | * 25 | * You must do this by modifying the input array in-place with O(1) 26 | * extra memory. 27 | */ 28 | public int removeElement(int[] nums, int val) 29 | { 30 | if( nums.length == 0) 31 | { 32 | return 0; 33 | } 34 | 35 | int validSize = 0; 36 | for(int i = 0; i < nums.length; i++) 37 | { 38 | if(nums[i] != val) 39 | { 40 | nums[validSize] = nums[i]; 41 | validSize++; 42 | } 43 | } 44 | return validSize; 45 | }// end of method removeElement 46 | }// end of class LeetCode 47 | -------------------------------------------------------------------------------- /romanToInteger.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.HashMap; 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Class LeetCode.java 7 | * A class with solutions to leet code problems 8 | */ 9 | public class LeetCode 10 | { 11 | /** 12 | * https://leetcode.com/problems/roman-to-integer/ 13 | * Easy 14 | * problem 13 Roman To Integer 15 | * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 16 | * Symbol Value 17 | * I 1 18 | * V 5 19 | * X 10 20 | * L 50 21 | * C 100 22 | * D 500 23 | * M 1000 24 | * Given a roman numeral, convert it to an integer. 25 | * Hash table 26 | */ 27 | public int romanToInt(String s) 28 | { 29 | Map map = new HashMap(); 30 | map.put('I', 1); 31 | map.put('V', 5); 32 | map.put('X', 10); 33 | map.put('L', 50); 34 | map.put('C', 100); 35 | map.put('D', 500); 36 | map.put('M', 1000); 37 | 38 | int result = 0; 39 | for(int i = 0; i < s.length(); i++) 40 | { 41 | if( i > 0 && map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) 42 | { 43 | result = result + map.get(s.charAt(i)) - 2 * map.get(s.charAt(i - 1)); 44 | } 45 | else 46 | { 47 | result += map.get(s.charAt(i)); 48 | } 49 | } 50 | return result; 51 | }// end of method romanToInt 52 | }// end of class LeetCode 53 | -------------------------------------------------------------------------------- /searchInsertPosition.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Class LeetCode.java 3 | * A class with solutions to leet code problems 4 | */ 5 | public class LeetCode 6 | { 7 | /** 8 | * https://leetcode.com/problems/search-insert-position/ 9 | * problem 35 Search Insert Position 10 | * Easy 11 | * Given a sorted array of distinct integers and a target value, 12 | * return the index if the target is found. 13 | * If not, return the index where it would be if it were inserted 14 | * in order. You must write an algorithm with O(log n) 15 | * runtime complexity. 16 | * binary search 17 | */ 18 | public int searchInsert(int[] nums, int target) 19 | { 20 | int l = 0; 21 | int r = nums.length - 1; 22 | 23 | while(l <= r) 24 | { 25 | int midIndex = (l + r)/2; 26 | if(nums[midIndex] == target) 27 | { 28 | return midIndex; 29 | } 30 | else if(nums[midIndex] > target) 31 | { 32 | r = midIndex -1; 33 | } 34 | else 35 | { 36 | l = midIndex + 1; 37 | } 38 | } 39 | return l; 40 | }// end of method searchInsert 41 | }// end of class LeetCode 42 | -------------------------------------------------------------------------------- /sortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 5 | * problem 108 Convert Sorted Array to Binary Search Tree 6 | * Easy 7 | * Given an integer array nums where the elements are sorted 8 | * in ascending order, convert it to a height-balanced 9 | * binary search tree. 10 | * Array, Divide and Conquer. Tree, Binary-Tree 11 | */ 12 | public TreeNode sortedArrayToBST(int[] nums) 13 | { 14 | if(nums.length == 0) 15 | { 16 | return null; 17 | } 18 | return constructTreeFromArray(nums, 0, nums.length - 1); 19 | }// end of method sorted array to BST 20 | public TreeNode constructTreeFromArray(int[] nums, int left, int right) 21 | { 22 | if(left > right) 23 | { 24 | return null; 25 | } 26 | int midpoint = left + (right - left) / 2; 27 | TreeNode node = new TreeNode(nums[midpoint]); 28 | node.left = constructTreeFromArray(nums, left, midpoint -1); 29 | node.right = constructTreeFromArray(nums, midpoint + 1, right); 30 | return node; 31 | 32 | }// end of method construct tree from array 33 | }// end of class LeetCode 34 | -------------------------------------------------------------------------------- /twoSum.java: -------------------------------------------------------------------------------- 1 | import java.util.Map; 2 | import java.util.HashMap; 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Class LeetCode.java 7 | * A class with solutions to leet code problems 8 | */ 9 | public class LeetCode 10 | { 11 | /**https://leetcode.com/problems/two-sum/ 12 | * problem 1 Two Sum 13 | * Given an array of integers nums and an integer target, 14 | * return indices of the two numbers such that they add up to target. 15 | * example 16 | * Input: nums = [2,7,11,15], target = 9 17 | * Output: [0,1] 18 | * Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 19 | */ 20 | public int[] twoSum(int[] nums, int target) 21 | { 22 | // first way brute force algorithm 23 | int[] indices = new int[2]; 24 | for(int i = 0; i < nums.length; i++) 25 | { 26 | for(int j = i + 1; j < nums.length; j++) 27 | { 28 | if(nums[i] + nums[j] == target) 29 | { 30 | indices[0] = i; 31 | indices[1] = j; 32 | } 33 | } 34 | } 35 | return indices; 36 | }// end of method twoSum 37 | // second method 38 | public int[] twoSum2(int[] nums, int target) 39 | { 40 | // second way using a hashmap 41 | Map map_nums = new HashMap<>(); 42 | for(int i = 0; i < nums.length; i++) 43 | { 44 | int complement = target - nums[i]; 45 | if(map_nums.containsKey(complement)) 46 | { 47 | return new int[] {map_nums.get(complement), i}; 48 | } 49 | map_nums.put(nums[i], i); 50 | } 51 | throw new IllegalArgumentException("no match found!"); 52 | }// end of method twoSum2 53 | }// end of class LeetCode 54 | -------------------------------------------------------------------------------- /validPalindrome.java: -------------------------------------------------------------------------------- 1 | public class LeetCode 2 | { 3 | /** 4 | * https://leetcode.com/problems/valid-palindrome/ 5 | * problem 125 Valid Palindrome 6 | * Easy 7 | * A phrase is a palindrome if, after converting all uppercase letters 8 | * into lowercase letters and removing all non-alphanumeric characters, 9 | * it reads the same forward and backward. 10 | * Alphanumeric characters include letters and numbers. Given a string s, 11 | * return true if it is a palindrome, or false otherwise. 12 | * Two Pointers, String 13 | */ 14 | public boolean isPalindrome(String s) 15 | { 16 | String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase(); 17 | String rev = new StringBuffer(actual).reverse().toString(); 18 | return actual.equals(rev); 19 | }// end of method isPalindrome 20 | }// end of class LeetCode 21 | --------------------------------------------------------------------------------