Skip to content

python solutions provided: #261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"python.formatting.provider": "black"
}
30 changes: 30 additions & 0 deletions 3 Sum/PythonSoution3Sum.py
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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))
46 changes: 46 additions & 0 deletions Remove Node From End/PythonSolutionRemoveNthFromEnd.py
Original file line number Diff line number Diff line change
@@ -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()

83 changes: 83 additions & 0 deletions Reverse Linked List/PythonSolutionReverseLinkedList.py
Original file line number Diff line number Diff line change
@@ -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()
176 changes: 160 additions & 16 deletions Reverse Linked List/cppSolutionReverseLinkedList.cpp
Original file line number Diff line number Diff line change
@@ -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 <bits/stdc++.h>
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 <bits/stdc++.h>
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;
}
Loading