diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..836fcaf --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.formatting.provider": "black" +} \ No newline at end of file diff --git a/3 Sum/PythonSoution3Sum.py b/3 Sum/PythonSoution3Sum.py new file mode 100644 index 0000000..57809e2 --- /dev/null +++ b/3 Sum/PythonSoution3Sum.py @@ -0,0 +1,30 @@ +# Problem Link: https://leetcode.com/problems/3sum/ + + +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + nums.sort() + result = [] + for i in range(len(nums) - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + l = i + 1 + r = len(nums) - 1 + while l < r: + if nums[i] + nums[l] + nums[r] == 0: + result.append([nums[i], nums[l], nums[r]]) + l += 1 + r -= 1 + while l < r and nums[l] == nums[l - 1]: + l += 1 + while l < r and nums[r] == nums[r + 1]: + r -= 1 + elif nums[i] + nums[l] + nums[r] < 0: + l += 1 + else: + r -= 1 + return result + + +# Time: O(n^2) +# Space: O(1) \ No newline at end of file diff --git a/Product of Array Except Self/PythonSolutionProductArrayExceptSef.py b/Product of Array Except Self/PythonSolutionProductArrayExceptSef.py new file mode 100644 index 0000000..63e47a4 --- /dev/null +++ b/Product of Array Except Self/PythonSolutionProductArrayExceptSef.py @@ -0,0 +1,41 @@ +# Question: https://leetcode.com/problems/product-of-array-except-self + + +from typing import List + + +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + # Solution 1 - O(n) time and O(n) space + # product = 1 + # for i in range(len(nums)): + # product *= nums[i] + # result = [product // nums[i] for i in range(len(nums))] + # return result + + # Solution 2 - O(n) time and O(1) space + # left = [1] * len(nums) + # right = [1] * len(nums) + # for i in range(1, len(nums)): + # left[i] = left[i - 1] * nums[i - 1] + # for i in range(len(nums) - 2, -1, -1): + # right[i] = right[i + 1] * nums[i + 1] + # result = [left[i] * right[i] for i in range(len(nums))] + # return result + + # Solution 3 - O(n) time and O(1) space + result = [1] * len(nums) + left = 1 + for i in range(len(nums)): + result[i] *= left + left *= nums[i] + right = 1 + for i in range(len(nums) - 1, -1, -1): + result[i] *= right + right *= nums[i] + return result + + +if __name__ == "__main__": + nums = [1, 2, 3, 4] + print(Solution().productExceptSelf(nums)) \ No newline at end of file diff --git a/Remove Node From End/PythonSolutionRemoveNthFromEnd.py b/Remove Node From End/PythonSolutionRemoveNthFromEnd.py new file mode 100644 index 0000000..20674e6 --- /dev/null +++ b/Remove Node From End/PythonSolutionRemoveNthFromEnd.py @@ -0,0 +1,46 @@ +# Remove nth node from end of list +# Given a linked list, remove the nth node from the end of list and return its head. + + +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: + if head is None: + return None + if head.next is None: + return None + if n == 0: + return head + if n == 1: + return head.next + current = head + count = 0 + while current is not None: + current = current.next + count += 1 + if count == n: + return head.next + current = head + for i in range(count - n - 1): + current = current.next + current.next = current.next.next + return head + + +def main(): + head = ListNode(1) + head.next = ListNode(2) + head.next.next = ListNode(3) + head.next.next.next = ListNode(4) + head.next.next.next.next = ListNode(5) + print(Solution().removeNthFromEnd(head, 2)) + + +if __name__ == '__main__': + main() + \ No newline at end of file diff --git a/Reverse Linked List/PythonSolutionReverseLinkedList.py b/Reverse Linked List/PythonSolutionReverseLinkedList.py new file mode 100644 index 0000000..a0a05e9 --- /dev/null +++ b/Reverse Linked List/PythonSolutionReverseLinkedList.py @@ -0,0 +1,83 @@ +## Reverse Linked List Problem Leetcode link : https://leetcode.com/problems/reverse-linked-list + + +""" +Reverse a singly linked list. + + +Example: + + +Input: 1->2->3->4->5->NULL +Output: 5->4->3->2->1->NULL +Follow up: + + +A linked list can be reversed either iteratively or recursively. Could you implement both? +""" + + +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +## Let's do it iteratively +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if not head: + return None + prev = None + curr = head + while curr: + next = curr.next + curr.next = prev + prev = curr + curr = next + return prev + + +# Time Complexity: O(n) +# Space Complexity: O(1) + + +## Let's do it recursively +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if not head or not head.next: + return head + new_head = self.reverseList(head.next) + head.next.next = head + head.next = None + return new_head + + +# Time Complexity: O(n) +# Space Complexity: O(n) + + +## Let's do it iteratively + + +# Time Complexity: O(n) +# Space Complexity: O(1) + + + + +def main(): + head = ListNode(1) + head.next = ListNode(2) + head.next.next = ListNode(3) + head.next.next.next = ListNode(4) + head.next.next.next.next = ListNode(5) + head.next.next.next.next.next = None + + print(Solution().reverseList(head)) + + + + +if __name__ == "__main__": + main() diff --git a/Reverse Linked List/cppSolutionReverseLinkedList.cpp b/Reverse Linked List/cppSolutionReverseLinkedList.cpp index b8573b1..69050b4 100644 --- a/Reverse Linked List/cppSolutionReverseLinkedList.cpp +++ b/Reverse Linked List/cppSolutionReverseLinkedList.cpp @@ -1,17 +1,161 @@ -#Reverse Linked List Problem Leetcode link : https://leetcode.com/problems/reverse-linked-list - -ListNode* reverseList(ListNode* head) { - ListNode* prevptr = NULL; - ListNode* currptr = head; - ListNode* nextptr ; - - while(currptr != NULL){ - nextptr = currptr->next; - currptr->next = prevptr; - - prevptr = currptr; - currptr = nextptr; - } - - return prevptr; +// Reverse Linked List Problem Leetcode link : https://leetcode.com/problems/reverse-linked-list + +/* +Reverse a singly linked list. + + +Example: + + +Input: 1->2->3->4->5->NULL +Output: 5->4->3->2->1->NULL +Follow up: + + +A linked list can be reversed either iteratively or recursively. Could you implement both? +*/ + +// C++ program to reverse a linked list +#include +using namespace std; + +// Node class +class Node +{ +public: + int data; + Node *next; + Node(int data) + { + this->data = data; + this->next = NULL; + } +}; + +// Function to reverse a linked list +Node *reverse(Node *head) +{ + // Base case + if (head == NULL || head->next == NULL) + return head; + + // Recur for remaining list + Node *p = reverse(head->next); + + // Modify head and move head to next node + head->next->next = head; + head->next = NULL; + + return p; +} + +// Function to print a linked list +void printList(Node *head) +{ + while (head != NULL) + { + cout << head->data << " "; + head = head->next; } +} + +// Driver program +int main() +{ + Node *head = new Node(1); + head->next = new Node(2); + head->next->next = new Node(3); + head->next->next->next = new Node(4); + head->next->next->next->next = new Node(5); + + cout << "Given linked list \n"; + printList(head); + + head = reverse(head); + + cout << "\nReversed linked list \n"; + printList(head); + + return 0; +} + +// let's try to it iteratively + +// C++ program to reverse a linked list +#include +using namespace std; + +// Node class +class Node +{ +public: + int data; + Node *next; + Node(int data) + { + this->data = data; + this->next = NULL; + } +}; + +// Function to reverse a linked list in an iterative way +Node *reverse(Node *head) +{ + // Base case + if (head == NULL || head->next == NULL) + return head; + + // Initialize prev, curr and next + Node *prev = NULL; + Node *curr = head; + Node *next = NULL; + + // Traverse the list + while (curr != NULL) + { + // Store next + next = curr->next; + + // Reverse current node's pointer + curr->next = prev; + + // Move pointers one position ahead. + prev = curr; + curr = next; + } + + // Update head pointer + head = prev; + + return head; +} + +// Function to print a linked list +void printList(Node *head) +{ + while (head != NULL) + { + cout << head->data << " "; + head = head->next; + } +} + +// Driver program +int main() +{ + Node *head = new Node(1); + head->next = new Node(2); + head->next->next = new Node(3); + head->next->next->next = new Node(4); + head->next->next->next->next = new Node(5); + + cout << "Given linked list \n"; + printList(head); + + head = reverse(head); + + cout << "\nReversed linked list \n"; + printList(head); + + return 0; +} diff --git a/Spiral Matrix/javaSolutionSpiralMatrix.java b/Spiral Matrix/javaSolutionSpiralMatrix.java index d4fac03..ef42b73 100644 --- a/Spiral Matrix/javaSolutionSpiralMatrix.java +++ b/Spiral Matrix/javaSolutionSpiralMatrix.java @@ -1,40 +1,78 @@ -Problem Link: https://leetcode.com/problems/spiral-matrix/ +// Problem Link: https://leetcode.com/problems/spiral-matrix/ -public List spiralOrder(int[][] matrix) { - int minR=0,minC=0; - int maxR=matrix.length-1; - int maxC=matrix[0].length-1; - int count=0; - int total=matrix.length*matrix[0].length; - List spiralTraversal=new ArrayList<>(); - - while(count spiralOrder(int[][] matrix) { + List result = new ArrayList<>(); + if (matrix.length == 0) { + return result; + } + int rowBegin = 0; + int rowEnd = matrix.length - 1; + int colBegin = 0; + int colEnd = matrix[0].length - 1; + while (rowBegin <= rowEnd && colBegin <= colEnd) { + for (int i = colBegin; i <= colEnd; i++) { + result.add(matrix[rowBegin][i]); } - minR++; - - for(int i=minR,j=maxC;i<=maxR && count=minC && count= colBegin; i--) { + result.add(matrix[rowEnd][i]); + } } - maxR--; - - for(int i=maxR,j=minC;i>=minR && count= rowBegin; i--) { + result.add(matrix[i][colBegin]); + } } - minC++; - + colBegin++; } - return spiralTraversal; + return result; } +} + + + +// public List spiralOrder(int[][] matrix) { +// int minR=0,minC=0; +// int maxR=matrix.length-1; +// int maxC=matrix[0].length-1; +// int count=0; +// int total=matrix.length*matrix[0].length; +// List spiralTraversal=new ArrayList<>(); + +// while(count=minC && count=minR && count List[int]: + return sorted([x ** 2 for x in nums]) + + +class Solution2: + def sortedSquares(self, nums: List[int]) -> List[int]: + n = len(nums) + i, j = 0, n - 1 + out = [0] * n + for k in range(n): + if abs(nums[i]) > abs(nums[j]): + out[k] = nums[i] ** 2 + i += 1 + else: + out[k] = nums[j] ** 2 + j -= 1 + return out + + +if __name__ == "__main__": + s = Solution() + s2 = Solution2() + print(s.sortedSquares([-4, -1, 0, 3, 10])) + print(s.sortedSquares([-7, -3, 2, 3, 11])) + print(s2.sortedSquares([-4, -1, 0, 3, 10])) + print(s2.sortedSquares([-7, -3, 2, 3, 11])) + diff --git a/Two Sum/PythonSolutionTwoSum.py b/Two Sum/PythonSolutionTwoSum.py new file mode 100644 index 0000000..c996ebb --- /dev/null +++ b/Two Sum/PythonSolutionTwoSum.py @@ -0,0 +1,29 @@ +# Question Link :- https://leetcode.com/problems/two-sum/ + + +from typing import List + + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + if nums[i] + nums[j] == target: + return [i, j] + +# Time Complexity :- O(n^2) +# Space Complexity :- O(1) + + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + dict = {} + for i in range(len(nums)): + if nums[i] in dict: + return [dict[nums[i]], i] + else: + dict[target - nums[i]] = i + +# Time Complexity :- O(n) +# Space Complexity :- O(n) +