Skip to content
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
Binary file not shown.
37 changes: 37 additions & 0 deletions data_structures_and_algorithms/challenges/merge_sort/merge_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
def merge_sort(arr):
n = len(arr)
# split the array in half
if n == 1:
return arr
if n == 0:
return "Not a valid input"
if n > 1:
mid = n//2
left = arr[:mid]
right = arr[mid:]
# sort the left side
merge_sort(left)
# sort the right side
merge_sort(right)
# sort them together in the correct order
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1

# Checking if any element was left
while i < len(left):
arr[k] = left[i]
i += 1
k += 1

while j < len(right):
arr[k] = right[j]
j += 1
k += 1
return arr
63 changes: 63 additions & 0 deletions data_structures_and_algorithms/challenges/merge_sort/read.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@

<h2>Merge Sort</h2>

<h3>About :</h3>
<pre>
Merge Sort is a Divide &Conquer Alogrithm.

It divides input array in two halves,calls itself for the two halves.
the merge(arr,l,m,r) is key process that assumes that arr{i....m} and arr{m+1...r}
are sorted and merge the two sorted is sub arrays into one.
</pre>

<h3>What do you mean by " Divide and Conquer approach"?</h3>

<pre>
A <b>Divide-and-conquer Algorithm</b> works by recursively breaking down a problem into two or more
sub-problems of the same or related type, until these become simple enough to be solved directly.

The solutions to the sub-problems are then combined to give a solution to the original problem.

The array is split in half and the process is repeated with each half until each half is of size 1 or 0.

The array of size 1 is trivially sorted.

Now the two sorted arrays are combined into one big array. And this is continued until all the elements are combined and the array is sorted.
</pre>
<h3>Time complexity</h3>

The algorithm works in <b>O(n.logn)</b>. This is because the list is being split in log(n) calls and the merging process takes linear time in each call.

<b>Auxiliary Space:</b> O(n)

<b>Algorithmic Paradigm:</b> Divide and Conquer

<b>Sorting In Place:</b> No in a typical implementation

<b>Stable:</b> Yes


<h3>Applications :</h3>
<pre>
1) Merge Sort is useful for sorting linked lists in O(nLogn) time.
2)Inversion Count Problem
3)Used in External Sorting
</pre>


<h3>Pseudocode :</h3>
<pre>
<b>MergeSort(arr[], l, r)</b>
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)



</pre>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Stacks and Queues

we created a data structure called **Stack** and **Queue** in Python. We used three classes, _Node_ and _Queue_, and _Stack_.

### Challenge
- Write queue and stack classes with their methods

## Approach & Efficiency
Stack :
- Define a method called push
- Define a method called pop
- Define a method called peek

Queue:
- Define a method called enqueue
- Define a method called dequeue
- Define a method called peek big
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
class Node:
def __init__(self, value):
self.value = value
self.next = None

def __repr__(self):
return f'{self.value}'


class Stack:

def __init__(self):
'''initialize stack with top, bottom and length'''
self.top = None
self.bottom = None
self.length = 0

def isEmpty(self):
return self.top == None

def push(self, value):
'''adds new node to top of stack by pointing it to self.top'''
node = Node(value)
node.next = self.top
self.top = node
self.length += 1

def pop(self):
'''Takes item from top of stack and returns it by reassigning the current top
to the next item in the stack. Stores the value in a temp variable to be returned'''
if self.length <= 0:
print('nothing to pop')
return

temp = self.top
self.top = self.top.next
popped = temp.value
self.length -= 1
return popped

def peek(self):
'''prints and returns the top of the stack'''
if self.length <= 0:
print('nothing to peek')
return
print(self.top.value)
return self.top.value


class Queue:

def __init__(self):
'''initializes a queue instance'''
self.front = None
self.rear = None
self.length = 0

def isEmpty(self):
return self.front == None

def enqueue(self, value):
'''appends value to front of queue'''

self.length += 1
new_node = Node(value)

if self.rear == None:
self.front = self.rear = new_node

return

self.rear.next = new_node
self.rear = new_node

def dequeue(self):
'''removes value from front of queue, if length is zero it returns the queue
and prints a message'''
self.length -= 1

if self.isEmpty():
self.queue = []
print('queue is empty')
return self.queue

temp = self.front
self.front = temp.next

if self.front == None:
self.rear = None

return str(temp.value)

def peek(self):
'''returns the first value in a queue'''
return self.front.value
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
from stacks_and_queues import Node, Stack, Queue

def test_empty_stack():
test_stack = Stack()
assert isinstance(test_stack, Stack)

def test_push():
test_stack = Stack()
test_stack.push(1)
test_stack.push(2)
assert test_stack.top.value == 2

def test_muliple_nodes():
test_stack = Stack()
test_stack.push(1)
test_stack.push(2)
test_stack.push(3)
assert test_stack.length == 3

def test_pop():
test_stack = Stack()
test_stack.push(1)
test_stack.push(2)
test_stack.push(3)
popped = test_stack.pop()
assert popped == 3
assert test_stack.length == 2
assert test_stack.top.value == 2

def test_multipop():
test_stack = Stack()
test_stack.push(1)
test_stack.push(2)
test_stack.push(3)
test_stack.pop()
test_stack.pop()
test_stack.pop()
assert test_stack.length == 0
assert test_stack.bottom == None

def test_peek():
test_stack = Stack()
test_stack.push(1)
test_stack.push(2)
test_stack.push(3)

assert test_stack.peek() == 3

def test_enqueue():
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)

assert q.front.value == 1

def test_enqueue_multiple():
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)

assert q.length == 3

def test_dequeue():
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.dequeue()

assert q.length == 2
assert q.front.value == 2

def test_enqueue_empty_queue():
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.dequeue()
q.dequeue()
q.dequeue()

assert q.length == 0

def test_instantiate_empty():
q = Queue()

assert q.length == 0
assert q.front == None


def test_q_peek():
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)

assert q.peek() == 1
Binary file not shown.
76 changes: 76 additions & 0 deletions data_structures_and_algorithms/data_structures/tree/resd.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
Tree Traversals (Inorder, Preorder and Postorder)
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Following are the generally used ways for traversing trees.



Depth First Traversals:
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1

Breadth First or Level Order Traversal : 1 2 3 4 5
Please see this post for Breadth First Traversal.

Inorder Traversal :

Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Uses of Inorder
In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal s reversed can be used.


Preorder Traversal :

Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Uses of Preorder
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on of an expression tree.

Postorder Traversal :

Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
Uses of Postorder
Postorder traversal is used to delete the tree. Please see the question for deletion of tree for details. Postorder traversal is also useful to get the postfix expression of an expression tree.


Time Complexity: O(n)
Complexity function T(n) — for all problem where tree traversal is involved — can be defined as:

T(n) = T(k) + T(n – k – 1) + c

Where k is the number of nodes on one side of root and n-k-1 on the other side.

Let’s do an analysis of boundary conditions

Case 1: Skewed tree (One of the subtrees is empty and other subtree is non-empty )

k is 0 in this case.
T(n) = T(0) + T(n-1) + c
T(n) = 2T(0) + T(n-2) + 2c
T(n) = 3T(0) + T(n-3) + 3c
T(n) = 4T(0) + T(n-4) + 4c

…………………………………………
………………………………………….
T(n) = (n-1)T(0) + T(1) + (n-1)c
T(n) = nT(0) + (n)c

Value of T(0) will be some constant say d. (traversing a empty tree will take some constants time)

T(n) = n(c+d)
T(n) = Θ(n) (Theta of n)

Case 2: Both left and right subtrees have equal number of nodes.

T(n) = 2T(|_n/2_|) + c

This recursive function is in the standard form (T(n) = aT(n/b) + (-)(n) )

Auxiliary Space : If we don’t consider size of stack for function calls then O(1) otherwise O(n).
Loading