code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
# Python3 program to find middle of linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Print the linked list def printList(self): node = self.head while node: print(str(node.data) + "->", end="") node = node.next print("NULL") # Function that returns middle. def printMiddle(self): # Initialize two pointers, one will go one step a time (slow), another two at a time (fast) slow = self.head fast = self.head # Iterate till fast's next is null (fast reaches end) while fast and fast.next: slow = slow.next fast = fast.next.next # return the slow's data, which would be the middle element. print("The middle element is ", slow.data) # Code execution starts here if __name__=='__main__': # Start with the empty list llist = LinkedList() for i in range(5, 0, -1): llist.push(i) llist.printList() llist.printMiddle() # Code is contributed by Kumar Shivam (kshivi99)
constant
linear
# Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Print the linked list def printList(self): node = self.head while node: print(str(node.data) + "->", end = "") node = node.next print("NULL") # Function to get the middle of # the linked list def printMiddle(self): count = 0 mid = self.head heads = self.head while(heads != None): # Update mid, when 'count' # is odd number if count&1: mid = mid.next count += 1 heads = heads.next # If empty list is provided if mid!=None: print("The middle element is ", mid.data) # Code execution starts here if __name__=='__main__': # Start with the empty list llist = LinkedList() for i in range(5, 0, -1): llist.push(i) llist.printList() llist.printMiddle() # This Code is contributed by Manisha_Ediga
constant
linear
# Python 3 program to find the number # of nodes in loop in a linked list # if loop is present # Python Code to detect a loop and # find the length of the loop # Node defining class class Node: # Function to make a node def __init__(self, val): self.val = val self.next = None # Linked List defining and loop # length finding class class LinkedList: # Function to initialize the # head of the linked list def __init__(self): self.head = None # Function to insert a new # node at the end def AddNode(self, val): if self.head is None: self.head = Node(val) else: curr = self.head while(curr.next): curr = curr.next curr.next = Node(val) # Function to create a loop in the # Linked List. This function creates # a loop by connecting the last node # to n^th node of the linked list, # (counting first node as 1) def CreateLoop(self, n): # LoopNode is the connecting node to # the last node of linked list LoopNode = self.head for _ in range(1, n): LoopNode = LoopNode.next # end is the last node of the Linked List end = self.head while(end.next): end = end.next # Creating the loop end.next = LoopNode # Function to detect the loop and return # the length of the loop if the returned # value is zero, that means that either # the linked list is empty or the linked # list doesn't have any loop def detectLoop(self): # if linked list is empty then there # is no loop, so return 0 if self.head is None: return 0 # Using Floyd’s Cycle-Finding # Algorithm/ Slow-Fast Pointer Method slow = self.head fast = self.head flag = 0 # to show that both slow and fast # are at start of the Linked List while(slow and slow.next and fast and fast.next and fast.next.next): if slow == fast and flag != 0: # Means loop is confirmed in the # Linked List. Now slow and fast # are both at the same node which # is part of the loop count = 1 slow = slow.next while(slow != fast): slow = slow.next count += 1 return count slow = slow.next fast = fast.next.next flag = 1 return 0 # No loop # Setting up the code # Making a Linked List and adding the nodes myLL = LinkedList() myLL.AddNode(1) myLL.AddNode(2) myLL.AddNode(3) myLL.AddNode(4) myLL.AddNode(5) # Creating a loop in the linked List # Loop is created by connecting the # last node of linked list to n^th node # 1<= n <= len(LinkedList) myLL.CreateLoop(2) # Checking for Loop in the Linked List # and printing the length of the loop loopLength = myLL.detectLoop() if myLL.head is None: print("Linked list is empty") else: print(str(loopLength)) # This code is contributed by _Ashutosh
constant
linear
# Python3 program to check if linked # list is palindrome using stack class Node: def __init__(self, data): self.data = data self.ptr = None # Function to check if the linked list # is palindrome or not def ispalindrome(head): # Temp pointer slow = head # Declare a stack stack = [] ispalin = True # Push all elements of the list # to the stack while slow != None: stack.append(slow.data) # Move ahead slow = slow.ptr # Iterate in the list again and # check by popping from the stack while head != None: # Get the top most element i = stack.pop() # Check if data is not # same as popped element if head.data == i: ispalin = True else: ispalin = False break # Move ahead head = head.ptr return ispalin # Driver Code # Addition of linked list one = Node(1) two = Node(2) three = Node(3) four = Node(4) five = Node(3) six = Node(2) seven = Node(1) # Initialize the next pointer # of every current pointer one.ptr = two two.ptr = three three.ptr = four four.ptr = five five.ptr = six six.ptr = seven seven.ptr = None # Call function to check palindrome or not result = ispalindrome(one) print("isPalindrome:", result) # This code is contributed by Nishtha Goel
linear
linear
# Python3 program to check if # linked list is palindrome # Node class class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to check if given # linked list is palindrome or not def isPalindrome(self, head): slow_ptr = head fast_ptr = head prev_of_slow_ptr = head # To handle odd size list midnode = None # Initialize result res = True if (head != None and head.next != None): # Get the middle of the list. # Move slow_ptr by 1 and # fast_ptr by 2, slow_ptr # will have the middle node while (fast_ptr != None and fast_ptr.next != None): # We need previous of the slow_ptr # for linked lists with odd # elements fast_ptr = fast_ptr.next.next prev_of_slow_ptr = slow_ptr slow_ptr = slow_ptr.next # fast_ptr would become NULL when # there are even elements in the # list and not NULL for odd elements. # We need to skip the middle node for # odd case and store it somewhere so # that we can restore the original list if (fast_ptr != None): midnode = slow_ptr slow_ptr = slow_ptr.next # Now reverse the second half # and compare it with first half second_half = slow_ptr # NULL terminate first half prev_of_slow_ptr.next = None # Reverse the second half second_half = self.reverse(second_half) # Compare res = self.compareLists(head, second_half) # Construct the original list back # Reverse the second half again second_half = self.reverse(second_half) if (midnode != None): # If there was a mid node (odd size # case) which was not part of either # first half or second half. prev_of_slow_ptr.next = midnode midnode.next = second_half else: prev_of_slow_ptr.next = second_half return res # Function to reverse the linked list # Note that this function may change # the head def reverse(self, second_half): prev = None current = second_half next = None while current != None: next = current.next current.next = prev prev = current current = next second_half = prev return second_half # Function to check if two input # lists have same data def compareLists(self, head1, head2): temp1 = head1 temp2 = head2 while (temp1 and temp2): if (temp1.data == temp2.data): temp1 = temp1.next temp2 = temp2.next else: return 0 # Both are empty return 1 if (temp1 == None and temp2 == None): return 1 # Will reach here when one is NULL # and other is not return 0 # Function to insert a new node # at the beginning def push(self, new_data): # Allocate the Node & # Put in the data new_node = Node(new_data) # Link the old list of the new one new_node.next = self.head # Move the head to point to new Node self.head = new_node # A utility function to print # a given linked list def printList(self): temp = self.head while(temp): print(temp.data, end="->") temp = temp.next print("NULL") # Driver code if __name__ == '__main__': l = LinkedList() s = ['a', 'b', 'a', 'c', 'a', 'b', 'a'] for i in range(7): l.push(s[i]) if (l.isPalindrome(l.head) != False): print("Is Palindrome\n") else: print("Not Palindrome\n") # This code is contributed by MuskanKalra1
constant
linear
# Python program for the above approach # Head of the list head = None left = None class Node: def __init__(self, val): self.data = val self.next = None # Initial parameters to this function are # &head and head def isPalindromeUtil(right): global head, left left = head # Stop recursion when right becomes null if (right == None): return True # If sub-list is not palindrome then no need to # check for the current left and right, return # false isp = isPalindromeUtil(right.next) if (isp == False): return False # Check values at current left and right isp1 = (right.data == left.data) left = left.next # Move left to next node; return isp1 # A wrapper over isPalindrome(Node head) def isPalindrome(head): result = isPalindromeUtil(head) return result # Push a node to linked list. Note that # this function changes the head def push(new_data): global head # Allocate the node and put in the data new_node = Node(new_data) # Link the old list off the the new one new_node.next = head # Move the head to point to new node head = new_node # A utility function to print a # given linked list def printList(ptr): while (ptr != None): print(ptr.data, end="->") ptr = ptr.next print("Null ") # Driver Code str = ['a', 'b', 'a', 'c', 'a', 'b', 'a'] for i in range(0, 7): push(str[i]) if (isPalindrome(head) and i != 0): print("Is Palindrome\n") else: print("Not Palindrome\n") # This code is contributed by saurabh_jaiswal.
linear
linear
# Python3 code to move the last item to front class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None # Function to add a node # at the beginning of Linked List def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node # Function to print nodes in a # given linked list def printList(self): tmp = self.head while tmp is not None: print(tmp.data, end=", ") tmp = tmp.next print() # Function to bring the last node to the front def moveToFront(self): tmp = self.head sec_last = None # To maintain the track of # the second last node # To check whether we have not received # the empty list or list with a single node if not tmp or not tmp.next: return # Iterate till the end to get # the last and second last node while tmp and tmp.next: sec_last = tmp tmp = tmp.next # point the next of the second # last node to None sec_last.next = None # Make the last node as the first Node tmp.next = self.head self.head = tmp # Driver's Code if __name__ == '__main__': llist = LinkedList() # swap the 2 nodes llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) print("Linked List before moving last to front ") llist.printList() # Function call llist.moveToFront() print("Linked List after moving last to front ") llist.printList()
constant
linear
''' Link list node ''' class Node: def __init__(self): self.data = 0 self.next = None '''This solution uses the temporary dummy to build up the result list ''' def sortedIntersect(a, b): dummy = Node() tail = dummy; dummy.next = None; ''' Once one or the other list runs out -- we're done ''' while (a != None and b != None): if (a.data == b.data): tail.next = push((tail.next), a.data); tail = tail.next; a = a.next; b = b.next; # advance the smaller list elif(a.data < b.data): a = a.next; else: b = b.next; return (dummy.next); ''' UTILITY FUNCTIONS ''' ''' Function to insert a node at the beginning of the linked list ''' def push(head_ref, new_data): ''' allocate node ''' new_node = Node() ''' put in the data ''' new_node.data = new_data; ''' link the old list off the new node ''' new_node.next = (head_ref); ''' move the head to point to the new node ''' (head_ref) = new_node; return head_ref ''' Function to print nodes in a given linked list ''' def printList(node): while (node != None): print(node.data, end=' ') node = node.next; ''' Driver code''' if __name__=='__main__': ''' Start with the empty lists ''' a = None; b = None; intersect = None; ''' Let us create the first sorted linked list to test the functions Created linked list will be 1.2.3.4.5.6 ''' a = push(a, 6); a = push(a, 5); a = push(a, 4); a = push(a, 3); a = push(a, 2); a = push(a, 1); ''' Let us create the second sorted linked list Created linked list will be 2.4.6.8 ''' b = push(b, 8); b = push(b, 6); b = push(b, 4); b = push(b, 2); ''' Find the intersection two linked lists ''' intersect = sortedIntersect(a, b); print("Linked list containing common items of a & b "); printList(intersect); # This code is contributed by rutvik_56.
linear
linear
# Python3 program to implement above approach # Link list node class Node: def __init__(self, d): self.data = d self.next = None def sortedIntersect(a, b): result = Node(0) curr = result # Advance comparing the first # nodes in both lists. # When one or the other list runs # out, we're done. while (a != None and b != None): if (a.data == b.data): # found a node for the intersection curr.next = Node(a.data) curr = curr.next a = a.next b = b.next elif (a.data < b.data): a = a.next # advance the smaller list else: b = b.next result = result.next return result # UTILITY FUNCTIONS # Function to insert a node at the beginning of the linked list def push(head_ref, new_data): # Allocate node new_node = Node(new_data) # Link the old list of the new node new_node.next = head_ref # Move the head to point to the new node head_ref = new_node return head_ref # Function to print nodes in a given linked list def printList(node): while (node != None): print(node.data, end=" ") node = node.next # Driver code # Start with the empty lists a = None b = None intersect = None # Let us create the first sorted linked list to test the functions Created # linked list will be 1.2.3.4.5.6 a = push(a, 6) a = push(a, 5) a = push(a, 4) a = push(a, 3) a = push(a, 2) a = push(a, 1) # Let us create the second sorted linked list Created linked list will be # 2.4.6.8 b = push(b, 8) b = push(b, 6) b = push(b, 4) b = push(b, 2) # Find the intersection two linked lists intersect = sortedIntersect(a, b) print("Linked list containing " + "common items of a & b") printList(intersect) # This code is contributed by Abhijeet Kumar(abhijeet19403)
linear
linear
# Link list node class Node: def __init__(self): self.data = 0 self.next = None def sortedIntersect(a, b): # base case if (a == None or b == None): return None # If both lists are non-empty # Advance the smaller list and call recursively if (a.data < b.data): return sortedIntersect(a.next, b); if (a.data > b.data): return sortedIntersect(a, b.next); # Below lines are executed only # when a.data == b.data temp = Node(); temp.data = a.data; # Advance both lists and call recursively temp.next = sortedIntersect(a.next, b.next); return temp; # UTILITY FUNCTIONS # Function to insert a node at the beginning of the linked list def push(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data; # Link the old list of the new node new_node.next = head_ref; # Move the head to point to the new node head_ref = new_node; return head_ref; # Function to print nodes in a given linked list def printList(node): while (node != None): print(node.data, end=" ") node = node.next; # Driver code # Start with the empty lists a = None b = None intersect = None # Let us create the first sorted linked list to test the functions Created # linked list will be 1.2.3.4.5.6 a = push(a, 6) a = push(a, 5) a = push(a, 4) a = push(a, 3) a = push(a, 2) a = push(a, 1) # Let us create the second sorted linked list Created linked list will be # 2.4.6.8 b = push(b, 8) b = push(b, 6) b = push(b, 4) b = push(b, 2) # Find the intersection two linked lists intersect = sortedIntersect(a, b) print("\n Linked list containing " + "common items of a & b"); printList(intersect) # This code is contributed by Saurabh Jaiswal
linear
linear
# Python3 program to implement above approach # Link list node class Node: def __init__(self): self.data = 0 self.next = None def printList(node): while (node != None): print(node.data, end=" ") node = node.next; def append(head_ref, new_data): new_node = Node() new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; def intersection(tmp1,tmp2,k): res = [0]*k set1 = set() while (tmp1 != None): set1.add(tmp1.data) tmp1 = tmp1.next cnt = 0 while (tmp2 != None): if tmp2.data in set1: res[cnt] = tmp2.data; cnt += 1 tmp2 = tmp2.next return res def printList(node): while (node != None): print(node.data, end=" ") node = node.next; # Driver code # Start with the empty lists ll = None ll1 = None ll = append(ll , 7) ll = append(ll , 6) ll = append(ll , 5) ll = append(ll , 4) ll = append(ll , 3) ll = append(ll , 2) ll = append(ll , 1) ll = append(ll , 0) ll1 = append(ll1 , 7) ll1 = append(ll1 , 6) ll1 = append(ll1 , 5) ll1 = append(ll1 , 4) ll1 = append(ll1 , 3) ll1 = append(ll1 , 12) ll1 = append(ll1 , 0) ll1 = append(ll1 , 9) arr = intersection(ll , ll1 , 6) for i in range(6): print(arr[i]) # This code is contributed by Abhijeet Kumar(abhijeet19403)
linear
linear
''' sort a linked list using quick sort ''' class Node: def __init__(self, val): self.data = val self.next = None class QuickSortLinkedList: def __init__(self): self.head = None def addNode(self, data): if (self.head == None): self.head = Node(data) return curr = self.head while (curr.next != None): curr = curr.next newNode = Node(data) curr.next = newNode def printList(self, n): while (n != None): print(n.data, end=" ") n = n.next ''' takes first and last node,but do not break any links in the whole linked list''' def paritionLast(self, start, end): if (start == end or start == None or end == None): return start pivot_prev = start curr = start pivot = end.data '''iterate till one before the end, no need to iterate till the end because end is pivot''' while (start != end): if (start.data < pivot): # keep tracks of last modified item pivot_prev = curr temp = curr.data curr.data = start.data start.data = temp curr = curr.next start = start.next '''swap the position of curr i.e. next suitable index and pivot''' temp = curr.data curr.data = pivot end.data = temp ''' return one previous to current because current is now pointing to pivot ''' return pivot_prev def sort(self, start, end): if(start == None or start == end or start == end.next): return # split list and partition recurse pivot_prev = self.paritionLast(start, end) self.sort(start, pivot_prev) ''' if pivot is picked and moved to the start, that means start and pivot is same so pick from next of pivot ''' if(pivot_prev != None and pivot_prev == start): self.sort(pivot_prev.next, end) # if pivot is in between of the list,start from next of pivot, # since we have pivot_prev, so we move two nodes elif (pivot_prev != None and pivot_prev.next != None): self.sort(pivot_prev.next.next, end) if __name__ == "__main__": ll = QuickSortLinkedList() ll.addNode(30) ll.addNode(3) ll.addNode(4) ll.addNode(20) ll.addNode(5) N = ll.head while (N.next != None): N = N.next print("\nLinked List before sorting") ll.printList(ll.head) # Function call ll.sort(ll.head, N) print("\nLinked List after sorting") ll.printList(ll.head) # This code is contributed by humpheykibet.
linear
nlogn
# Python3 program to check if a linked list is circular # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__(self): self.head = None def Circular(head): if head == None: return True # Next of head node = head.next i = 0 # This loop would stop in both cases (1) If # Circular (2) Not circular while((node is not None) and (node is not head)): i = i + 1 node = node.next return(node == head) # Driver's code if __name__ == '__main__': llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) fourth = Node(4) llist.head.next = second second.next = third third.next = fourth if (Circular(llist.head)): print('Yes') else: print('No') fourth.next = llist.head if (Circular(llist.head)): print('Yes') else: print('No') # This code is contributed by Sanket Badhe
constant
linear
// C Program to convert a Binary Tree // to a Circular Doubly Linked List #include <stdio.h> #include <stdlib.h> // To represents a node of a Binary Tree typedef struct Node { struct Node *left, *right; int data; } Node; // A function that appends rightList at the end // of leftList. Node* concatenate(Node* leftList, Node* rightList) { // If either of the list is empty // then return the other list if (leftList == NULL) return rightList; if (rightList == NULL) return leftList; // Store the last Node of left List Node* leftLast = leftList->left; // Store the last Node of right List Node* rightLast = rightList->left; // Connect the last node of Left List // with the first Node of the right List leftLast->right = rightList; rightList->left = leftLast; // Left of first node points to // the last node in the list leftList->left = rightLast; // Right of last node refers to the first // node of the List rightLast->right = leftList; return leftList; } // Function converts a tree to a circular Linked List // and then returns the head of the Linked List Node* bTreeToCList(Node* root) { if (root == NULL) return NULL; // Recursively convert left and right subtrees Node* left = bTreeToCList(root->left); Node* right = bTreeToCList(root->right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root->left = root->right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List void displayCList(Node* head) { printf("Circular Linked List is :\n"); Node* itr = head; do { printf("%d ", itr->data); itr = itr->right; } while (head != itr); printf("\n"); } // Create a new Node and return its address Node* newNode(int data) { Node* temp = (Node*)malloc(sizeof(Node)); temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver Program to test above function int main() { Node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); Node* head = bTreeToCList(root); displayCList(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
logn
linear
# Python3 Program to convert a Binary # Tree to a Circular Doubly Linked List class newNode: def __init__(self, data): self.data = data self.left = self.right = None # A function that appends rightList # at the end of leftList. def concatenate(leftList, rightList): # If either of the list is empty # then return the other list if (leftList == None): return rightList if (rightList == None): return leftList # Store the last Node of left List leftLast = leftList.left # Store the last Node of right List rightLast = rightList.left # Connect the last node of Left List # with the first Node of the right List leftLast.right = rightList rightList.left = leftLast # Left of first node points to # the last node in the list leftList.left = rightLast # Right of last node refers to # the first node of the List rightLast.right = leftList return leftList # Function converts a tree to a circular # Linked List and then returns the head # of the Linked List def bTreeToCList(root): if (root == None): return None # Recursively convert left and # right subtrees left = bTreeToCList(root.left) right = bTreeToCList(root.right) # Make a circular linked list of single # node (or root). To do so, make the # right and left pointers of this node # point to itself root.left = root.right = root # Step 1 (concatenate the left list # with the list with single # node, i.e., current node) # Step 2 (concatenate the returned list # with the right List) return concatenate(concatenate(left, root), right) # Display Circular Link List def displayCList(head): print("Circular Linked List is :") itr = head first = 1 while (head != itr or first): print(itr.data, end=" ") itr = itr.right first = 0 print() # Driver Code if __name__ == '__main__': root = newNode(10) root.left = newNode(12) root.right = newNode(15) root.left.left = newNode(25) root.left.right = newNode(30) root.right.left = newNode(36) head = bTreeToCList(root) displayCList(head) # This code is contributed by PranchalK
logn
linear
# Python3 program to find last man standing # /* structure for a node in circular # linked list */ class Node: def __init__(self, x): self.data = x self.next = None # /* Function to find the only person left # after one in every m-th node is killed # in a circle of n nodes */ def getJosephusPosition(m, n): # Create a circular linked list of # size N. head = Node(1) prev = head for i in range(2, n + 1): prev.next = Node(i) prev = prev.next prev.next = head # Connect last #node to first #/* while only one node is left in the #linked list*/ ptr1 = head ptr2 = head while (ptr1.next != ptr1): # Find m-th node count = 1 while (count != m): ptr2 = ptr1 ptr1 = ptr1.next count += 1 # /* Remove the m-th node */ ptr2.next = ptr1.next # free(ptr1) ptr1 = ptr2.next print("Last person left standing (Josephus Position) is ", ptr1.data) # /* Driver program to test above functions */ if __name__ == '__main__': n = 14 m = 2 getJosephusPosition(m, n) # This code is contributed by mohit kumar 29
linear
quadratic
# Python3 program for converting # singly linked list into # circular linked list. import sys # Linked list node class Node: def __init__(self,data): self.data = data self.next = None def push(head, data): if not head: return Node(data) # Allocate dynamic memory # for newNode. # Assign the data into newNode. newNode = Node(data) # newNode.next assign the # address of head node. newNode.next = head # newNode become the headNode. head = newNode return head # Function that convert # singly linked list into # circular linked list. def circular(head): # declare a node variable # start and assign head # node into start node. start = head # check that while head.next # not equal to null then head # points to next node. while(head.next is not None): head = head.next # if head.next points to null # then start assign to the # head.next node. head.next = start return start # Function that display the elements # of circular linked list. def displayList(node): start = node while(node.next is not start): print("{} ".format(node.data),end="") node=node.next # Display the last node of # circular linked list. print("{} ".format(node.data),end="") # Driver Code if __name__=='__main__': # Start with empty list head=None # Using push() function to # convert singly linked list # 17.22.13.14.15 head=push(head,15) head=push(head,14) head=push(head,13) head=push(head,22) head=push(head,17) # Call the circular_list function # that convert singly linked # list to circular linked list. circular(head) print("Display List:") displayList(head) # This Code is Contributed By Vikash Kumar 37
constant
linear
# Python implementation of De-queue using circular # array # A structure to represent a Deque MAX = 100 class Deque: def __init__(self, size): self.arr = [0] * MAX self.front = -1 self.rear = 0 self.size = size ''' Operations on Deque: void insertfront(int key); void insertrear(int key); void deletefront(); void deleterear(); bool isFull(); bool isEmpty(); int getFront(); int getRear(); ''' # Checks whether Deque is full or not. def isFull(self): return ((self.front == 0 and self.rear == self.size-1) or self.front == self.rear + 1) # Checks whether Deque is empty or not. def isEmpty(self): return (self.front == -1) # Inserts an element at front def insertfront(self, key): # check whether Deque if full or not if (self.isFull()): print("Overflow") return # If queue is initially empty if (self.front == -1): self.front = 0 self.rear = 0 # front is at first position of queue elif (self.front == 0): self.front = self.size - 1 else: # decrement front end by '1' self.front = self.front-1 # insert current element into Deque self.arr[self.front] = key # function to inset element at rear end # of Deque. def insertrear(self, key): if (self.isFull()): print(" Overflow") return # If queue is initially empty if (self.front == -1): self.front = 0 self.rear = 0 # rear is at last position of queue elif (self.rear == self.size-1): self.rear = 0 # increment rear end by '1' else: self.rear = self.rear+1 # insert current element into Deque self.arr[self.rear] = key # Deletes element at front end of Deque def deletefront(self): # check whether Deque is empty or not if (self.isEmpty()): print("Queue Underflow") return # Deque has only one element if (self.front == self.rear): self.front = -1 self.rear = -1 else: # back to initial position if (self.front == self.size - 1): self.front = 0 else: # increment front by '1' to remove current # front value from Deque self.front = self.front+1 # Delete element at rear end of Deque def deleterear(self): if (self.isEmpty()): print(" Underflow") return # Deque has only one element if (self.front == self.rear): self.front = -1 self.rear = -1 elif (self.rear == 0): self.rear = self.size-1 else: self.rear = self.rear-1 # Returns front element of Deque def getFront(self): # check whether Deque is empty or not if (self.isEmpty()): print(" Underflow") return -1 return self.arr[self.front] # function return rear element of Deque def getRear(self): # check whether Deque is empty or not if(self.isEmpty() or self.rear < 0): print(" Underflow") return -1 return self.arr[self.rear] # Driver code if __name__ == "__main__": dq = Deque(5) # Function calls print("Insert element at rear end : 5 ") dq.insertrear(5) print("insert element at rear end : 10 ") dq.insertrear(10) print(f"get rear element : {dq.getRear()}") dq.deleterear() print(f"After delete rear element new rear become : {dq.getRear()}") print("inserting element at front end") dq.insertfront(15) print(f"get front element: {dq.getFront()}") dq.deletefront() print(f"After delete front element new front become : {dq.getFront()}") # This code is contributed by _saurabh_jaiswal
linear
linear
# Python program to exchange first and # last node in circular linked list class Node { class Node: def __init__(self): self.data = 0 self.next = None def addToEmpty(head, data): # This function is only for empty list if (head != None): return head # Creating a node dynamically. temp = Node() # Assigning the data. temp.data = data head = temp # Creating the link. head.next = head return head def addBegin(head, data): if (head == None): return addToEmpty(head, data) temp = Node() temp.data = data temp.next = head.next head.next = temp return head # function for traversing the list def traverse(head): # If list is empty, return. if (head == None): print("List is empty.") return # Pointing to first Node of the list. p = head # Traversing the list. while (True): print(p.data, end=" ") p = p.next if(p == head): break # Function to exchange first and last node def exchangeNodes(head): # If list is of length less than 2 if (head == None or head.next == None): return head tail = head # Find pointer to the last node while (tail.next != head): tail = tail.next # Exchange first and last nodes using head and p # temporary variable to store # head data temp = tail.data tail.data = head.data head.data = temp return head # Driven Program head = None head = addToEmpty(head, 6) for i in range(5, 0, -1): head = addBegin(head, i) print("List Before: ") traverse(head) print("") print("List After: ") head = exchangeNodes(head) traverse(head) # This code is contributed by Saurabh Jaiswal
constant
linear
# Program to delete a node in a doubly-linked list # for Garbage collection import gc # A node of the doubly linked list class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: # Constructor for empty Doubly Linked List def __init__(self): self.head = None # Function to delete a node in a Doubly Linked List. # head_ref --> pointer to head node pointer. # dele --> pointer to node to be deleted def deleteNode(self, dele): # Base Case if self.head is None or dele is None: return # If node to be deleted is head node if self.head == dele: self.head = dele.next # Change next only if node to be deleted is NOT # the last node if dele.next is not None: dele.next.prev = dele.prev # Change prev only if node to be deleted is NOT # the first node if dele.prev is not None: dele.prev.next = dele.next # Finally, free the memory occupied by dele # Call python garbage collector gc.collect() # Given a reference to the head of a list and an # integer, inserts a new node on the front of list def push(self, new_data): # 1. Allocates node # 2. Put the data in it new_node = Node(new_data) # 3. Make next of new node as head and # previous as None (already None) new_node.next = self.head # 4. change prev of head node to new_node if self.head is not None: self.head.prev = new_node # 5. move the head to point to the new node self.head = new_node def printList(self, node): while(node is not None): print(node.data,end=' ') node = node.next # Driver program to test the above functions # Start with empty list dll = DoublyLinkedList() # Let us create the doubly linked list 10<->8<->4<->2 dll.push(2); dll.push(4); dll.push(8); dll.push(10); print ("\n Original Linked List",end=' ') dll.printList(dll.head) # delete nodes from doubly linked list dll.deleteNode(dll.head) dll.deleteNode(dll.head.next) dll.deleteNode(dll.head.next) # Modified linked list will be NULL<-8->NULL print("\n Modified Linked List",end=' ') dll.printList(dll.head) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
constant
constant
# Python3 Program to reverse a doubly linked list # A node of the doubly linked list class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: # Constructor for empty Doubly Linked List def __init__(self): self.head = None # Function reverse a Doubly Linked List def reverse(self): temp = None current = self.head # Swap next and prev for all nodes of # doubly linked list while current is not None: temp = current.prev current.prev = current.next current.next = temp current = current.prev # Before changing head, check for the cases like # empty list and list with only one node if temp is not None: self.head = temp.prev # Given a reference to the head of a list and an # integer,inserts a new node on the front of list def push(self, new_data): # 1. Allocates node # 2. Put the data in it new_node = Node(new_data) # 3. Make next of new node as head and # previous as None (already None) new_node.next = self.head # 4. change prev of head node to new_node if self.head is not None: self.head.prev = new_node # 5. move the head to point to the new node self.head = new_node def printList(self, node): while(node is not None): print(node.data, end=' ') node = node.next # Driver's code if __name__ == "__main__": dll = DoublyLinkedList() dll.push(2) dll.push(4) dll.push(8) dll.push(10) print("\nOriginal Linked List") dll.printList(dll.head) # Function call dll.reverse() print("\nReversed Linked List") dll.printList(dll.head) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
constant
linear
# Python3 code for the above approach class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None """ method to reverse a Doubly-Linked List using Stacks """ def reverseUsingStacks(self): stack = [] temp = self.head while temp is not None: stack.append(temp.data) temp = temp.next # Add all the elements in the stack # in a sequence to the stack temp = self.head while temp is not None: temp.data = stack.pop() temp = temp.next # Popped all the elements and the # added in the linked list, # in a reversed order. """ method to push a new item before the head """ def push(self, new_data): new_node = Node(new_data) new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node """ method to traverse the doubly-linked list and print every node in the list """ def printList(self, node): while(node is not None): print(node.data) node = node. next # driver's code if __name__ == "__main__": dll = DoublyLinkedList() dll.push(2) dll.push(4) dll.push(8) dll.push(10) print("original doubly-linked list") dll.printList(dll.head) # Function call dll.reverseUsingStacks() print(" reversed doubly-linked list") dll.printList(dll.head)
linear
linear
# Program for merge sort on doubly linked list # A node of the doubly linked list class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: # Constructor for empty Doubly Linked List def __init__(self): self.head = None # Function to merge two linked list def merge(self, first, second): # If first linked list is empty if first is None: return second # If second linked list is empty if second is None: return first # Pick the smaller value if first.data < second.data: first.next = self.merge(first.next, second) first.next.prev = first first.prev = None return first else: second.next = self.merge(first, second.next) second.next.prev = second second.prev = None return second # Function to do merge sort def mergeSort(self, tempHead): if tempHead is None: return tempHead if tempHead.next is None: return tempHead second = self.split(tempHead) # Recur for left and right halves tempHead = self.mergeSort(tempHead) second = self.mergeSort(second) # Merge the two sorted halves return self.merge(tempHead, second) # Split the doubly linked list (DLL) into two DLLs # of half sizes def split(self, tempHead): fast = slow = tempHead while(True): if fast.next is None: break if fast.next.next is None: break fast = fast.next.next slow = slow.next temp = slow.next slow.next = None return temp # Given a reference to the head of a list and an # integer,inserts a new node on the front of list def push(self, new_data): # 1. Allocates node # 2. Put the data in it new_node = Node(new_data) # 3. Make next of new node as head and # previous as None (already None) new_node.next = self.head # 4. change prev of head node to new_node if self.head is not None: self.head.prev = new_node # 5. move the head to point to the new node self.head = new_node def printList(self, node): temp = node print ("Forward Traversal using next pointer") while(node is not None): print (node.data,end=" ") temp = node node = node.next print ("\nBackward Traversal using prev pointer") while(temp): print (temp.data,end=" ") temp = temp.prev # Driver program to test the above functions dll = DoublyLinkedList() dll.push(5) dll.push(20); dll.push(4); dll.push(3); dll.push(30) dll.push(10); dll.head = dll.mergeSort(dll.head) print ("Linked List after sorting") dll.printList(dll.head) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
constant
nlogn
# Python3 program to create a doubly linked # list out of given a ternary tree. # Custom node class. class newNode: def __init__(self, data): self.data = data self.left = None self.right = None self.middle = None class GFG: def __init__(self): # Tail of the linked list. self.tail = None # Function to push the node to the tail. def push(self, node): # To put the node at the end of # the already existing tail. self.tail.right = node # To point to the previous node. node.left = self.tail # Middle pointer should point to # nothing so null. initiate right # pointer to null. node.middle = node.right = None # Update the tail position. self.tail = node # Create a doubly linked list out of given # a ternary tree By traversing the tree in # preorder fashion. def ternaryTree(self, node, head): if node == None: return left = node.left middle = node.middle right = node.right if self.tail != node: # Already root is in the tail so dont push # the node when it was root.In the first # case both node and tail have root in them. self.push(node) # First the left child is to be taken. # Then middle and then right child. self.ternaryTree(left, head) self.ternaryTree(middle, head) self.ternaryTree(right, head) def startTree(self, root): # Initiate the head and tail with root. head = root self.tail = root self.ternaryTree(root, head) # Since the head,root are passed # with reference the changes in # root will be reflected in head. return head # Utility function for printing double linked list. def printList(self, head): print("Created Double Linked list is:") while head: print(head.data, end = " ") head = head.right # Driver code if __name__ == '__main__': # Constructing ternary tree as shown # in above figure root = newNode(30) root.left = newNode(5) root.middle = newNode(11) root.right = newNode(63) root.left.left = newNode(1) root.left.middle = newNode(4) root.left.right = newNode(8) root.middle.left = newNode(6) root.middle.middle = newNode(7) root.middle.right = newNode(15) root.right.left = newNode(31) root.right.middle = newNode(55) root.right.right = newNode(65) # The function which initiates the list # process returns the head. head = None gfg = GFG() head = gfg.startTree(root) gfg.printList(head) # This code is contributed by Winston Sebastian Pais
linear
linear
# Python3 program to find a pair with # given sum x. # Structure of node of doubly linked list class Node: def __init__(self, x): self.data = x self.next = None self.prev = None # Function to find pair whose sum # equal to given value x. def pairSum(head, x): # Set two pointers, first to the # beginning of DLL and second to # the end of DLL. first = head second = head while (second.next != None): second = second.next # To track if we find a pair or not found = False # The loop terminates when they # cross each other (second.next == # first), or they become same # (first == second) while (first != second and second.next != first): # Pair found if ((first.data + second.data) == x): found = True print("(", first.data, ",", second.data, ")") # Move first in forward direction first = first.next # Move second in backward direction second = second.prev else: if ((first.data + second.data) < x): first = first.next else: second = second.prev # If pair is not present if (found == False): print("No pair found") # A utility function to insert a new node # at the beginning of doubly linked list def insert(head, data): temp = Node(data) if not head: head = temp else: temp.next = head head.prev = temp head = temp return head # Driver code if __name__ == '__main__': head = None head = insert(head, 9) head = insert(head, 8) head = insert(head, 6) head = insert(head, 5) head = insert(head, 4) head = insert(head, 2) head = insert(head, 1) x = 7 pairSum(head, x) # This code is contributed by mohit kumar 29
constant
linear
# Python3 implementation to insert # value in sorted way in a sorted # doubly linked list # Node of a doubly linked list class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: # Function to initialize head def __init__(self): self.head = None # Function to create and return a # new node of a doubly linked list def getNode(self, data): return Node(data) # Function to insert a new node in # sorted way in a sorted doubly linked list def sortedInsert(self, data): new_node = self.getNode(data) # If the list is empty if self.head is None: self.head = new_node # If the node is to be inserted at # the beginning of the doubly linked list elif self.head.data >= new_node.data: new_node.next = self.head new_node.next.prev = new_node self.head = new_node else: current = self.head # Locate the node after which # the new node is to be inserted while ((current.next is not None) and (current.next.data < new_node.data)): current = current.next # Make the appropriate links new_node.next = current.next # If the new node is not inserted # at the end of the list if current.next is not None: new_node.next.prev = new_node current.next = new_node new_node.prev = current # Function to print the doubly linked list def printList(self): node = self.head while node: print(str(node.data), end = " ") node = node.next # Driver code if __name__ == '__main__': # Insert the following nodes # in sorted way llist = DoublyLinkedList() llist.sortedInsert(8) llist.sortedInsert(5) llist.sortedInsert(3) llist.sortedInsert(10) llist.sortedInsert(12) llist.sortedInsert(9) print("Created Doubly Linked List") llist.printList() # This code is contributed by Siddhartha Pramanik
linear
linear
# Python3 implementation to count triplets # in a sorted doubly linked list # whose sum is equal to a given value 'x' # structure of node of doubly linked list class Node: def __init__(self): self.data = None self.prev = None self.next = None # function to count triplets in a sorted doubly linked list # whose sum is equal to a given value 'x' def countTriplets( head, x): ptr1 = head ptr2 = None ptr3 = None count = 0 # generate all possible triplets while (ptr1 != None ): ptr2 = ptr1.next while ( ptr2 != None ): ptr3 = ptr2.next while ( ptr3 != None ): # if elements in the current triplet sum up to 'x' if ((ptr1.data + ptr2.data + ptr3.data) == x): # increment count count = count + 1 ptr3 = ptr3.next ptr2 = ptr2.next ptr1 = ptr1.next # required count of triplets return count # A utility function to insert a new node at the # beginning of doubly linked list def insert(head, data): # allocate node temp = Node() # put in the data temp.data = data temp.next = temp.prev = None if ((head) == None): (head) = temp else : temp.next = head (head).prev = temp (head) = temp return head # Driver code # start with an empty doubly linked list head = None # insert values in sorted order head = insert(head, 9) head = insert(head, 8) head = insert(head, 6) head = insert(head, 5) head = insert(head, 4) head = insert(head, 2) head = insert(head, 1) x = 17 print( "Count = ", countTriplets(head, x)) # This code is contributed by Arnab Kundu
constant
cubic
# Python3 implementation to count triplets in a sorted doubly linked list # whose sum is equal to a given value 'x' # structure of node of doubly linked list class Node: def __init__(self, data): self.data=data self.next=None self.prev=None # function to count triplets in a sorted doubly linked list # whose sum is equal to a given value 'x' def countTriplets(head, x): ptr2=head count = 0; # unordered_map 'um' implemented as hash table um = dict() ptr = head # insert the <node data, node pointer> tuple in 'um' while ptr!=None: um[ptr.data] = ptr; ptr = ptr.next # generate all possible pairs ptr1=head while ptr1!=None: ptr2 = ptr1.next while ptr2!=None: # p_sum - sum of elements in the current pair p_sum = ptr1.data + ptr2.data; # if 'x-p_sum' is present in 'um' and either of the two nodes # are not equal to the 'um[x-p_sum]' node if ((x-p_sum) in um) and um[x - p_sum] != ptr1 and um[x - p_sum] != ptr2: # increment count count+=1 ptr2 = ptr2.next ptr1 = ptr1.next # required count of triplets # division by 3 as each triplet is counted 3 times return (count // 3); # A utility function to insert a new node at the # beginning of doubly linked list def insert(head, data): # allocate node temp = Node(data); if ((head) == None): (head) = temp; else: temp.next = head; (head).prev = temp; (head) = temp; return head # Driver program to test above if __name__=='__main__': # start with an empty doubly linked list head = None; # insert values in sorted order head = insert(head, 9); head = insert(head, 8); head = insert(head, 6); head = insert(head, 5); head = insert(head, 4); head = insert(head, 2); head = insert( head, 1); x = 17; print("Count = "+ str(countTriplets(head, x))) # This code is contributed by rutvik_56
linear
quadratic
# Python3 implementation to count triplets # in a sorted doubly linked list whose sum # is equal to a given value 'x' # Structure of node of doubly linked list class Node: def __init__(self, x): self.data = x self.next = None self.prev = None # Function to count pairs whose sum # equal to given 'value' def countPairs(first, second, value): count = 0 # The loop terminates when either of two pointers # become None, or they cross each other (second.next # == first), or they become same (first == second) while (first != None and second != None and first != second and second.next != first): # Pair found if ((first.data + second.data) == value): # Increment count count += 1 # Move first in forward direction first = first.next # Move second in backward direction second = second.prev # If sum is greater than 'value' # move second in backward direction elif ((first.data + second.data) > value): second = second.prev # Else move first in forward direction else: first = first.next # Required count of pairs return count # Function to count triplets in a sorted # doubly linked list whose sum is equal # to a given value 'x' def countTriplets(head, x): # If list is empty if (head == None): return 0 current, first, last = head, None, None count = 0 # Get pointer to the last node of # the doubly linked list last = head while (last.next != None): last = last.next # Traversing the doubly linked list while current != None: # For each current node first = current.next # count pairs with sum(x - current.data) in # the range first to last and add it to the # 'count' of triplets count, current = count + countPairs( first, last, x - current.data), current.next # Required count of triplets return count # A utility function to insert a new node # at the beginning of doubly linked list def insert(head, data): # Allocate node temp = Node(data) # Put in the data # temp.next = temp.prev = None if (head == None): head = temp else: temp.next = head head.prev = temp head = temp return head # Driver code if __name__ == '__main__': # Start with an empty doubly linked list head = None # Insert values in sorted order head = insert(head, 9) head = insert(head, 8) head = insert(head, 6) head = insert(head, 5) head = insert(head, 4) head = insert(head, 2) head = insert(head, 1) x = 17 print("Count = ", countTriplets(head, x)) # This code is contributed by mohit kumar 29
constant
quadratic
# Python implementation to remove duplicates from a # sorted doubly linked list # A linked list node class Node: def __init__(self, new_data): self.data = new_data self.next = None self.prev = None # Function to _delete a node in a Doubly Linked List. # head_ref -. pointer to head node pointer. # _del -. pointer to node to be _deleted. def _deleteNode(head_ref, _del): # base case if (head_ref == None or _del == None): return # If node to be _deleted is head node if (head_ref == _del): head_ref = _del.next # Change next only if node to be _deleted # is NOT the last node if (_del.next != None): _del.next.prev = _del.prev # Change prev only if node to be _deleted # is NOT the first node if (_del.prev != None): _del.prev.next = _del.next return head_ref # function to remove duplicates from a # sorted doubly linked list def removeDuplicates(head_ref): # if list is empty if ((head_ref) == None): return None current = head_ref next = None # traverse the list till the last node while (current.next != None) : # Compare current node with next node if (current.data == current.next.data): # _delete the node pointed to by # 'current.next' _deleteNode(head_ref, current.next) # else simply move to the next node else: current = current.next return head_ref # Function to insert a node at the beginning # of the Doubly Linked List def push(head_ref, new_data): # allocate node new_node = Node(0) # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # Function to print nodes in a given doubly linked list def printList(head): # if list is empty if (head == None): print("Doubly Linked list empty") while (head != None) : print(head.data, end = " ") head = head.next # Driver program to test above functions # Start with the empty list head = None # Create the doubly linked list: # 4<->4<->4<->4<->6<->8<->8<->10<->12<->12 head = push(head, 12) head = push(head, 12) head = push(head, 10) head = push(head, 8) head = push(head, 8) head = push(head, 6) head = push(head, 4) head = push(head, 4) head = push(head, 4) head = push(head, 4) print( "Original Doubly linked list:\n") printList(head) # remove duplicate nodes head = removeDuplicates(head) print("\nDoubly linked list after removing duplicates:") printList(head) # This code is contributed by Arnab Kundu
constant
linear
# Python3 implementation to delete all occurrences # of a given key in a doubly linked list import math # a node of the doubly linked list class Node: def __init__(self,data): self.data = data self.next = None self.prev = None # Function to delete a node in a Doubly Linked List. # head_ref --> pointer to head node pointer. # del --> pointer to node to be deleted. def deleteNode(head, delete): # base case if (head == None or delete == None): return None # If node to be deleted is head node if (head == delete): head = delete.next # Change next only if node to be deleted # is NOT the last node if (delete.next != None): delete.next.prev = delete.prev # Change prev only if node to be deleted # is NOT the first node if (delete.prev != None): delete.prev.next = delete.next # Finally, free the memory occupied by del # free(del) delete = None return head # function to delete all occurrences of the given # key 'x' def deleteAllOccurOfX(head, x): # if list is empty if (head == None): return current = head # traverse the list up to the end while (current != None): # if node found with the value 'x' if (current.data == x): # save current's next node in the #pointer 'next' next = current.next # delete the node pointed to by # 'current' head = deleteNode(head, current) # update current current = next # else simply move to the next node else: current = current.next return head # Function to insert a node at the beginning # of the Doubly Linked List def push(head,new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # since we are adding at the beginning, #prev is always None new_node.prev = None # link the old list off the new node new_node.next = head # change prev of head node to new node if (head != None): head.prev = new_node # move the head to point to the new node head = new_node return head # Function to print nodes in a given doubly # linked list def printList(head): # if list is empty if (head == None): print("Doubly Linked list empty") while (head != None) : print(head.data,end=" ") head = head.next # Driver functions if __name__=='__main__': # Start with the empty list head = None # Create the doubly linked list: # 2<->2<->10<->8<->4<->2<->5<->2 head = push(head, 2) head = push(head, 5) head = push(head, 2) head = push(head, 4) head = push(head, 8) head = push(head, 10) head = push(head, 2) head = push(head, 2) print("Original Doubly linked list:") printList(head) x = 2 # delete all occurrences of 'x' head = deleteAllOccurOfX(head, x) print("\nDoubly linked list after deletion of ",x,":") printList(head) # This article contributed by Srathore
constant
linear
# Python implementation to remove duplicates # from an unsorted doubly linked list # Node of a linked list class Node: def __init__(self, data = None, next = None): self.next = next self.data = data # Function to delete a node in a Doubly Linked List. # head_ref -. pointer to head node pointer. # del -. pointer to node to be deleted. def deleteNode(head_ref,del_): # base case if (head_ref == None or del_ == None): return head_ref # If node to be deleted is head node if (head_ref == del_): head_ref = del_.next # Change next only if node to be deleted # is NOT the last node if (del_.next != None): del_.next.prev = del_.prev # Change prev only if node to be deleted # is NOT the first node if (del_.prev != None): del_.prev.next = del_.next return head_ref # function to remove duplicates from # an unsorted doubly linked list def removeDuplicates( head_ref): # if DLL is empty or if it contains only # a single node if ((head_ref) == None or (head_ref).next == None): return head_ref ptr1 = head_ref ptr2 = None # pick elements one by one while(ptr1 != None) : ptr2 = ptr1.next # Compare the picked element with the # rest of the elements while (ptr2 != None): # if duplicate, then delete it if (ptr1.data == ptr2.data): # store pointer to the node next to 'ptr2' next = ptr2.next # delete node pointed to by 'ptr2' head_ref = deleteNode(head_ref, ptr2) # update 'ptr2' ptr2 = next # else simply move to the next node else: ptr2 = ptr2.next ptr1 = ptr1.next return head_ref # Function to insert a node at the beginning # of the Doubly Linked List def push( head_ref, new_data): # allocate node new_node = Node() # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # Function to print nodes in a # given doubly linked list def printList( head): # if list is empty if (head == None): print("Doubly Linked list empty") while (head != None): print( head.data ,end= " ") head = head.next # Driver Code head = None # Create the doubly linked list: # 8<.4<.4<.6<.4<.8<.4<.10<.12<.12 head = push(head, 12) head = push(head, 12) head = push(head, 10) head = push(head, 4) head = push(head, 8) head = push(head, 4) head = push(head, 6) head = push(head, 4) head = push(head, 4) head = push(head, 8) print("Original Doubly linked list:") printList(head) # remove duplicate nodes */ head=removeDuplicates(head) print("\nDoubly linked list after removing duplicates:") printList(head) # This code is contributed by Arnab Kundu
constant
quadratic
# Python3 implementation to remove duplicates # from an unsorted doubly linked list # a node of the doubly linked list class Node: def __init__(self): self.data = 0 self.next = None self.prev = None # Function to delete a node in a Doubly Linked List. # head_ref --> pointer to head node pointer. # del --> pointer to node to be deleted. def deleteNode( head_ref, del_): # base case if (head_ref == None or del_ == None): return None # If node to be deleted is head node if (head_ref == del_): head_ref = del_.next # Change next only if node to be deleted # is NOT the last node if (del_.next != None): del_.next.prev = del_.prev # Change prev only if node to be deleted # is NOT the first node if (del_.prev != None): del_.prev.next = del_.next return head_ref # function to remove duplicates from # an unsorted doubly linked list def removeDuplicates(head_ref): # if doubly linked list is empty if ((head_ref) == None): return None # unordered_set 'us' implemented as hash table us = set() current = head_ref next = None # traverse up to the end of the list while (current != None): # if current data is seen before if ((current.data) in us): # store pointer to the node next to # 'current' node next = current.next # delete the node pointed to by 'current' head_ref = deleteNode(head_ref, current) # update 'current' current = next else: # insert the current data in 'us' us.add(current.data) # move to the next node current = current.next return head_ref # Function to insert a node at the # beginning of the Doubly Linked List def push(head_ref,new_data): # allocate node new_node = Node() # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # Function to print nodes in a given doubly # linked list def printList( head): # if list is empty if (head == None): print("Doubly Linked list empty") while (head != None): print(head.data , end=" ") head = head.next # Driver Code head = None # Create the doubly linked list: # 8<->4<->4<->6<->4<->8<->4<->10<->12<->12 head = push(head, 12) head = push(head, 12) head = push(head, 10) head = push(head, 4) head = push(head, 8) head = push(head, 4) head = push(head, 6) head = push(head, 4) head = push(head, 4) head = push(head, 8) print("Original Doubly linked list:") printList(head) # remove duplicate nodes head = removeDuplicates(head) print("\nDoubly linked list after removing duplicates:") printList(head) # This code is contributed by Arnab Kundu
linear
linear
# Python implementation to sort a k sorted doublyclass DoublyLinkedList { head = None class Node: def __init__(self, val): self.data = val self.prev = None self.next = None # function to sort a k sorted doubly linked list # Using Insertion Sort # Time Complexity: O(n*k) # Space Complexity: O(1) def sortAKSortedDLL(head , k): if (head == None or head.next == None): return head # perform on all the nodes in list i = head.next while(i != None): j = i # There will be atmost k swaps for each element in the list # since each node is k steps away from its correct position while (j.prev != None and j.data < j.prev.data): # swap j and j.prev node temp = j.prev.prev temp2 = j.prev temp3 = j.next j.prev.next = temp3 j.prev.prev = j j.prev = temp j.next = temp2 if (temp != None): temp.next = j if (temp3 != None): temp3.prev = temp2 # if j is now the new head # then reset head if (j.prev == None): head = j i = i.next return head # UTILITY FUNCTIONS # # Function to insert a node at the beginning of the Doubly Linked List def push(new_data): global head # allocate node new_node = Node(new_data) # # since we are adding at the beginning, prev is always NULL # new_node.prev = None # link the old list of the new node new_node.next = head # change prev of head node to new node if (head != None): head.prev = new_node # move the head to point to the new node head = new_node # Function to print nodes in a given doubly linked list This function is same # as printList() of singly linked list def printList(node): while (node != None): print(node.data,end = " ") node = node.next # Driver code # Let us create a k sorted doubly linked list to test the functions Created # doubly linked list will be 3<->6<->2<->12<->56<->8 push(8) push(56) push(12) push(2) push(6) push(3) k = 2 print("Original Doubly linked list:") printList(head) sortedDLL = sortAKSortedDLL(head, k) print("") print("Doubly Linked List after sorting:") printList(sortedDLL) # This codeis contributed by shinjanpatra
constant
quadratic
# Python implementation to sort a k sorted doubly linked list import heapq head = None # a node of the doubly linked list class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # function to sort a k sorted doubly linked list def sortAKSortedDLL(head, k): # if list is empty if head == None: return head pq = [] newHead = None last = None for i in range(k+1): # push the node heapq.heappush(pq, (head.data, head)) # move to the next node head = head.next # loop till there are elements in 'pq' while len(pq) > 0: if newHead == None: newHead = heapq.heappop(pq)[1] newHead.prev = None # 'last' points to the last node of the result sorted list so far last = newHead else: last.next = heapq.heappop(pq)[1] last.next.prev = last last = last.next # if there are more nodes left in the input list if head != None: # push the node heapq.heappush(pq, (head.data, head)) # move to the next node head = head.next # making 'next' of last node point to NULL last.next = None # new head of the required sorted DLL return newHead # Function to insert a node at the beginning of the Doubly Linked List def push(new_data): global head # allocate node new_node = Node(new_data) # since we are adding at the beginning, prev is always NULL new_node.prev = None # link the old list off the new node new_node.next = head # change prev of head node to new node if (head != None): head.prev = new_node # move the head to point to the new node head = new_node # Function to print nodes in a given doubly linked list def printList(head): # if list is empty if head is None: print("Doubly Linked list empty") while head is not None: print(head.data, end=" ") head = head.next # Driver code if __name__ == '__main__': # Create the doubly linked list: # 3<->6<->2<->12<->56<->8 push(8) push(56) push(12) push(2) push(6) push(3) k = 2 print("Original Doubly linked list:") printList(head) sortedDLL = sortAKSortedDLL(head, k) print("\nDoubly Linked List after sorting:") printList(sortedDLL) # This code is contributed by Tapesh(tapeshdua420)
constant
nlogn
# Python3 program to convert a given Binary Tree to Doubly Linked List class Node: def __init__(self, data): self.data = data self.left = self.right = None class BinaryTree: # A simple recursive function to convert a given # Binary tree to Doubly Linked List # root --> Root of Binary Tree # head --> Pointer to head node of created doubly linked list root, head = None, None def BToDll(self, root: Node): if root is None: return # Recursively convert right subtree self.BToDll(root.right) # Insert root into doubly linked list root.right = self.head # Change left pointer of previous head if self.head is not None: self.head.left = root # Change head of doubly linked list self.head = root # Recursively convert left subtree self.BToDll(root.left) @staticmethod def print_list(head: Node): print('Extracted Double Linked list is:') while head is not None: print(head.data, end = ' ') head = head.right # Driver program to test above function if __name__ == '__main__': """ Constructing below tree 5 // \\ 3 6 // \\ \\ 1 4 8 // \\ // \\ 0 2 7 9 """ tree = BinaryTree() tree.root = Node(5) tree.root.left = Node(3) tree.root.right = Node(6) tree.root.left.left = Node(1) tree.root.left.right = Node(4) tree.root.right.right = Node(8) tree.root.left.left.left = Node(0) tree.root.left.left.right = Node(2) tree.root.right.right.left = Node(7) tree.root.right.right.right = Node(9) tree.BToDll(tree.root) tree.print_list(tree.head) # This code is contributed by Rajat Srivastava
linear
linear
# Python program to insetail nodes in doubly # linked list such that list remains in # ascending order on printing from left # to right # Linked List node class Node: def __init__(self, data): self.info = data self.next = None self.prev = None head = None tail = None # Function to insetail new node def nodeInsetail( key) : global head global tail p = Node(0) p.info = key p.next = None # If first node to be insetailed in doubly # linked list if ((head) == None) : (head) = p (tail) = p (head).prev = None return # If node to be insetailed has value less # than first node if ((p.info) < ((head).info)) : p.prev = None (head).prev = p p.next = (head) (head) = p return # If node to be insetailed has value more # than last node if ((p.info) > ((tail).info)) : p.prev = (tail) (tail).next = p (tail) = p return # Find the node before which we need to # insert p. temp = (head).next while ((temp.info) < (p.info)) : temp = temp.next # Insert new node before temp (temp.prev).next = p p.prev = temp.prev temp.prev = p p.next = temp # Function to print nodes in from left to right def printList(temp) : while (temp != None) : print( temp.info, end = " ") temp = temp.next # Driver program to test above functions nodeInsetail( 30) nodeInsetail( 50) nodeInsetail( 90) nodeInsetail( 10) nodeInsetail( 40) nodeInsetail( 110) nodeInsetail( 60) nodeInsetail( 95) nodeInsetail( 23) print("Doubly linked list on printing from left to right\n" ) printList(head) # This code is contributed by Arnab Kundu
constant
linear
# Python code to rotate doubly linked list by N nodes. class Node: def __init__(self, data): self.data = data self.pre = None self.next = None class GFG: def __init__(self): self.head = None # Function to insert nodes at the start of the linked list. def insertAtHead(self, data): n = Node(data) if self.head == None: self.head = n return n.next = self.head self.head.pre = n self.head = n return # Function to insert nodes at the tail of the linked list. def insertAtTail(self, data): if self.head == None: self.insertAtHead(data) return temp = self.head while temp.next != None: temp = temp.next n = Node(data) temp.next = n n.pre = temp return # Function to print the list. def display(self): temp = self.head while temp != None: print(temp.data, "-->", sep="", end="") temp = temp.next print("NULL") # Function to rotate doubly linked list by N nodes. def rotateByN(self, pos): if pos == 0: return curr = self.head while pos: curr = curr.next pos -= 1 tail = curr.pre NewHead = curr tail.next = None curr.pre = None while curr.next != None: curr = curr.next curr.next = self.head self.head.pre = curr self.head = NewHead # Driver Code if __name__ == "__main__": list = GFG() list.insertAtTail('a') list.insertAtTail('b') list.insertAtTail('c') list.insertAtTail('d') list.insertAtTail('e') n = 2 print("Before Rotation : ") list.display() list.rotateByN(n) print("\nAfter Rotation : ") list.display() print() # This code is contributed by Tapesh(tapeshdua420)
constant
linear
class Node: def __init__(self): self.data = 0; self.next = None; self.next = None; # Function to add Node at the end of a # Doubly LinkedList def insertAtEnd(head, data): new_Node = Node(); new_Node.data = data; new_Node.next = None; temp = head; if (head == None): new_Node.prev = None; head = new_Node; return head; while (temp.next != None): temp = temp.next; temp.next = new_Node; new_Node.prev = temp; return head; # Function to print Doubly LinkedList def printDLL(head): while (head != None): print(head.data, end=" "); head = head.next; print(); # Function to Reverse a doubly linked list # in groups of given size def reverseByN(head, k): if (head == None): return None; head.prev = None; temp=None; curr = head; newHead = None; count = 0; while (curr != None and count < k): newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count += 1; # Checking if the reversed LinkedList size is # equal to K or not. If it is not equal to k # that means we have reversed the last set of # size K and we don't need to call the # recursive function if (count >= k): rest = reverseByN(curr, k); head.next = rest; if (rest != None): # it is required for prev link otherwise u # wont be backtrack list due to broken # links rest.prev = head; return newHead; # Driver code if __name__ == '__main__': head = None; for i in range(1,11): head = insertAtEnd(head, i); printDLL(head); n = 4; head = reverseByN(head, n); printDLL(head); # This code contributed by umadevi9616
constant
linear
# Python implementation to reverse a doubly # linked list in groups of given size without recursion # Iterative method. # Represents a node of doubly linked list. class Node: def __init__(self, data): self.data = data self.next = None # Function to get a new Node. def getNode(data): # allocating node new_node = Node(0) new_node.data = data new_node.next = new_node.prev = None return new_node # Function to insert a node at the beginning of the doubly linked list. def push(head, new_node): # since we are adding at the beginning, prev is always null. new_node.prev = None # link the old list off the new node. new_node.next = head # change prev of head node to new node. if ((head) != None): head.prev = new_node # move the head to point to the new node. head = new_node return head # Function to print nodes in given doubly linked list. def printList(head): while (head): print(head.data, end=" ") head = head.next # Function to reverse a doubly linked list in groups of given size. def revListInGroupOfGivenSize(head, k): if head is None: return head st = head globprev, ans = None, None while (st != None): # Count the number of nodes. count = 1 curr = st prev, next_node = None, None while (curr != None and count <= k): # Reversing k nodes. next_node = curr.next curr.prev = next_node curr.next = prev prev = curr curr = next_node count += 1 if ans is None: ans = prev ans.prev = None if globprev is None: globprev = st else: globprev.next = prev prev.prev = globprev globprev = st st = curr return ans # Start with the empty list. head = None # Create a doubly linked list: 10<->8<->4<->2 head = push(head, getNode(2)) head = push(head, getNode(4)) head = push(head, getNode(8)) head = push(head, getNode(10)) print("Original list:", end=" ") printList(head) k = 2 # Reverse doubly linked list in groups of size 'k' head = revListInGroupOfGivenSize(head, k) print("\nModified list:", end=" ") printList(head) # This code is contributed by lokesh (lokeshmvs21).
constant
linear
# Python3 program to implement Stack # using linked list so that reverse # can be done with O(1) extra space. class StackNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.top = None # Push and pop operations def push(self, data): if (self.top == None): self.top = StackNode(data) return s = StackNode(data) s.next = self.top self.top = s def pop(self): s = self.top self.top = self.top.next return s # Prints contents of stack def display(self): s = self.top while (s != None): print(s.data, end = ' ') s = s.next # Reverses the stack using simple # linked list reversal logic. def reverse(self): prev = self.top cur = self.top cur = cur.next succ = None prev.next = None while (cur != None): succ = cur.next cur.next = prev prev = cur cur = succ self.top = prev # Driver code if __name__=='__main__': s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) print("Original Stack") s.display() print() # Reverse s.reverse() print("Reversed Stack") s.display() # This code is contributed by rutvik_56
constant
linear
# Python3 program to find a list in second list class Node: def __init__(self, value = 0): self.value = value self.next = None # Returns true if first list is # present in second list def findList(first, second): # If both linked lists are empty/None, # return True if not first and not second: return True # If ONLY one of them is empty, # return False if not first or not second: return False ptr1 = first ptr2 = second # Traverse the second LL by # picking nodes one by one while ptr2: # Initialize 'ptr2' with current # node of 'second' ptr2 = second # Start matching first LL # with second LL while ptr1: # If second LL become empty and # first not, return False, # since first LL has not been # traversed completely if not ptr2: return False # If value of both nodes from both # LLs are equal, increment pointers # for both LLs so that next value # can be matched else if ptr1.value == ptr2.value: ptr1 = ptr1.next ptr2 = ptr2.next # If a single mismatch is found # OR ptr1 is None/empty,break out # of the while loop and do some checks else: break # check 1 : # If 'ptr1' is None/empty,that means # the 'first LL' has been completely # traversed and matched so return True if not ptr1: return True # If check 1 fails, that means, some # items for 'first' LL are still yet # to be matched, so start again by # bringing back the 'ptr1' to point # to 1st node of 'first' LL ptr1 = first # And increment second node element to next second = second.next return False # Driver Code # Let us create two linked lists to # test the above functions. # Created lists would be be # node_a: 1->2->3->4 # node_b: 1->2->1->2->3->4 node_a = Node(1) node_a.next = Node(2) node_a.next.next = Node(3) node_a.next.next.next = Node(4) node_b = Node(1) node_b.next = Node(2) node_b.next.next = Node(1) node_b.next.next.next = Node(2) node_b.next.next.next.next = Node(3) node_b.next.next.next.next.next = Node(4) if findList(node_a, node_b): print("LIST FOUND") else: print("LIST NOT FOUND") # This code is contributed by GauriShankarBadola
constant
quadratic
# Python3 program to implement unrolled # linked list and traversing it. maxElements = 4 # Unrolled Linked List Node class Node: def __init__(self): self.numElements = 0 self.array = [0 for i in range(maxElements)] self.next = None # Function to traverse an unrolled linked list # and print all the elements def printUnrolledList(n): while (n != None): # Print elements in current node for i in range(n.numElements): print(n.array[i], end = ' ') # Move to next node n = n.next # Driver Code if __name__=='__main__': head = None second = None third = None # Allocate 3 Nodes head = Node() second = Node() third = Node() # Let us put some values in second # node (Number of values must be # less than or equal to # maxElement) head.numElements = 3 head.array[0] = 1 head.array[1] = 2 head.array[2] = 3 # Link first Node with the second Node head.next = second # Let us put some values in second node # (Number of values must be less than # or equal to maxElement) second.numElements = 3 second.array[0] = 4 second.array[1] = 5 second.array[2] = 6 # Link second Node with the third Node second.next = third # Let us put some values in third node # (Number of values must be less than # or equal to maxElement) third.numElements = 3 third.array[0] = 7 third.array[1] = 8 third.array[2] = 9 third.next = None printUnrolledList(head) # This code is contributed by rutvik_56
linear
linear
# Python program to construct a Maximum Sum Linked List out of # two Sorted Linked Lists having some Common nodes class LinkedList(object): def __init__(self): # head of list self.head = None # Linked list Node class Node(object): def __init__(self, d): self.data = d self.next = None # Method to adjust pointers and print final list def finalMaxSumList(self, a, b): result = None # assigning pre and cur to head # of the linked list pre1 = a curr1 = a pre2 = b curr2 = b # Till either of current pointers is not null # execute the loop while curr1 != None or curr2 != None: # Keeping 2 local variables at the start of every # loop run to keep track of the sum between pre # and cur reference elements. sum1 = 0 sum2 = 0 # Calculating sum by traversing the nodes of linked # list as the merging of two linked list. The loop # stops at a common node while curr1 != None and curr2 != None and curr1.data != curr2.data: if curr1.data < curr2.data: sum1 += curr1.data curr1 = curr1.next else: sum2 += curr2.data curr2 = curr2.next # If either of current pointers becomes null # carry on the sum calculation for other one. if curr1 == None: while curr2 != None: sum2 += curr2.data curr2 = curr2.next if curr2 == None: while curr1 != None: sum1 += curr1.data curr1 = curr1.next # First time adjustment of resultant head based on # the maximum sum. if pre1 == a and pre2 == b: result = pre1 if (sum1 > sum2) else pre2 else: # If pre1 and pre2 don't contain the head references of # lists adjust the next pointers of previous pointers. if sum1 > sum2: pre2.next = pre1.next else: pre1.next = pre2.next # Adjusting previous pointers pre1 = curr1 pre2 = curr2 # If curr1 is not NULL move to the next. if curr1 != None: curr1 = curr1.next # If curr2 is not NULL move to the next. if curr2 != None: curr2 = curr2.next while result != None: print (str(result.data),end=" ") result = result.next print () # Utility functions # Inserts a new Node at front of the list. def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = self.Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Driver program llist1 = LinkedList() llist2 = LinkedList() # Linked List 1 : 1->3->30->90->110->120->NULL # Linked List 2 : 0->3->12->32->90->100->120->130->NULL llist1.push(120) llist1.push(110) llist1.push(90) llist1.push(30) llist1.push(3) llist1.push(1) llist2.push(130) llist2.push(120) llist2.push(100) llist2.push(90) llist2.push(32) llist2.push(12) llist2.push(3) llist2.push(0) llist1.finalMaxSumList(llist1.head, llist2.head) # This code is contributed by BHAVYA JAIN
constant
linear
# Python3 program to find fractional node # in a linked list import math # Linked list node class Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node # with given data def newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to find fractional node # in the linked list def fractionalNodes(head, k): # Corner cases if (k <= 0 or head == None): return None fractionalNode = None # Traverse the given list i = 0 temp = head while (temp != None): # For every k nodes, we move # fractionalNode one step ahead. if (i % k == 0): # First time we see a multiple of k if (fractionalNode == None): fractionalNode = head else: fractionalNode = fractionalNode.next i = i + 1 temp = temp.next return fractionalNode # A utility function to print a linked list def printList(node): while (node != None): print(node.data, end = ' ') node = node.next # Driver Code if __name__ == '__main__': head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(4) head.next.next.next.next = newNode(5) k = 2 print("List is", end = ' ') printList(head) answer = fractionalNodes(head, k) print("\nFractional node is", end = ' ') print(answer.data) # This code is contributed by Srathore
constant
linear
# Python3 program to find modular node # in a linked list import math # Linked list node class Node: def __init__(self, data): self.data = data self.next = None # Function to create a new node # with given data def newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to find modular node # in the linked list def modularNode(head, k): # Corner cases if (k <= 0 or head == None): return None # Traverse the given list i = 1 modularNode = None temp = head while (temp != None): if (i % k == 0): modularNode = temp i = i + 1 temp = temp.next return modularNode # Driver Code if __name__ == '__main__': head = newNode(1) head.next = newNode(2) head.next.next = newNode(3) head.next.next.next = newNode(4) head.next.next.next.next = newNode(5) k = 2 answer = modularNode(head, k) print("Modular node is", end = ' ') if (answer != None): print(answer.data, end = ' ') else: print("None") # This code is contributed by Srathore
constant
linear
# Python3 program to find smallest and largest # elements in singly linked list. # Linked list node class Node: def __init__(self): self.data = None self.next = None head = None # Function that returns the largest element # from the linked list. def largestElement(head): # Declare a max variable and initialize # it with INT_MIN value. # INT_MIN is integer type and its value # is -32767 or less. max = -32767 # Check loop while head not equal to None while (head != None): # If max is less than head.data then # assign value of head.data to max # otherwise node point to next node. if (max < head.data) : max = head.data head = head.next return max # Function that returns smallest element # from the linked list. def smallestElement(head): # Declare a min variable and initialize # it with INT_MAX value. # INT_MAX is integer type and its value # is 32767 or greater. min = 32767 # Check loop while head not equal to None while (head != None) : # If min is greater than head.data then # assign value of head.data to min # otherwise node point to next node. if (min > head.data) : min = head.data head = head.next return min # Function that push the element in linked list. def push( data) : global head # Allocate dynamic memory for newNode. newNode = Node() # Assign the data into newNode. newNode.data = data # newNode.next assign the address of # head node. newNode.next = (head) # newNode become the headNode. (head) = newNode # Display linked list. def printList( head) : while (head != None) : print(head.data ,end= " -> ") head = head.next print("None") # Driver code # Start with empty list # head = new Node() # Using push() function to construct # singly linked list # 17.22.13.14.15 push( 15) push( 14) push( 13) push( 22) push( 17) print("Linked list is : ") # Call printList() function to # display the linked list. printList(head) print("Maximum element in linked list: ",end="") # Call largestElement() function to get # largest element in linked list. print(largestElement(head)) print("Minimum element in linked list: ",end="") # Call smallestElement() function to get # smallest element in linked list. print(smallestElement(head),end="") # This code is contributed by Arnab Kundu
constant
linear
# Python3 program to remove vowels # Nodes in a linked list # A linked list node class Node: def __init__(self, x): self.data = x self.next = None # Utility function to print the # linked list def printlist(head): if (not head): print("Empty List") return while (head != None): print(head.data, end = " ") if (head.next): print(end = "-> ") head = head.next print() # Utility function for checking vowel def isVowel(x): return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U') #/* function to arrange consonants and # vowels nodes */ def arrange(head): newHead = head # for keep track of vowel latestVowel = None curr = head # list is empty if (head == None): return None # We need to discover the first vowel # in the list. It is going to be the # returned head, and also the initial # latestVowel. if (isVowel(head.data)): # first element is a vowel. It will # also be the new head and the initial # latestVowel latestVowel = head else: # First element is not a vowel. Iterate # through the list until we find a vowel. # Note that curr points to the element # *before* the element with the vowel. while (curr.next != None and not isVowel(curr.next.data)): curr = curr.next # This is an edge case where there are # only consonants in the list. if (curr.next == None): return head # Set the initial latestVowel and the # new head to the vowel item that we found. # Relink the chain of consonants after # that vowel item: # old_head_consonant.consonant1.consonant2. # vowel.rest_of_list becomes # vowel.old_head_consonant.consonant1. # consonant2.rest_of_list latestVowel = newHead = curr.next curr.next = curr.next.next latestVowel.next = head # Now traverse the list. Curr is always the item # *before* the one we are checking, so that we # can use it to re-link. while (curr != None and curr.next != None): if (isVowel(curr.next.data)): # The next discovered item is a vowel if (curr == latestVowel): # If it comes directly after the # previous vowel, we don't need to # move items around, just mark the # new latestVowel and advance curr. latestVowel = curr = curr.next else: # But if it comes after an intervening # chain of consonants, we need to chain # the newly discovered vowel right after # the old vowel. Curr is not changed as # after the re-linking it will have a # new next, that has not been checked yet, # and we always keep curr at one before # the next to check. temp = latestVowel.next # Chain in new vowel latestVowel.next = curr.next # Advance latestVowel latestVowel = latestVowel.next # Remove found vowel from previous place curr.next = curr.next.next # Re-link chain of consonants after latestVowel latestVowel.next = temp else: # No vowel in the next element, advance curr. curr = curr.next return newHead # Driver code if __name__ == '__main__': # Initialise the Linked List head = Node('a') head.next = Node('b') head.next.next = Node('c') head.next.next.next = Node('e') head.next.next.next.next = Node('d') head.next.next.next.next.next = Node('o') head.next.next.next.next.next.next = Node('x') head.next.next.next.next.next.next.next = Node('i') # Print the given Linked List print("Linked list before :") printlist(head) head = arrange(head) # Print the Linked List after # removing vowels print("Linked list after :") printlist(head) # This code is contributed by mohit kumar 29
constant
linear
''' Python program to arrange consonants and vowels Nodes in a linked list ''' ''' A linked list Node ''' class Node: def __init__(self, data): self.data = data; self.next = None; ''' Function to add new Node to the List ''' def append(headRef, data): new_Node = Node(data); last = headRef; if (headRef == None): headRef = new_Node; return headRef; while (last.next != None): last = last.next; last.next = new_Node; return headRef; # utility function to print linked list def printlist(head): if (head == None): print("Empty List"); return; while (head != None): print(head.data, end=""); if (head.next != None): print("-> ",end=""); head = head.next; print(); ''' * function to arrange consonants and vowels Nodes ''' def arrange(head): vowel = None; consonant = None; start = None; end = None; while (head != None): x = head.data; # Checking the current Node data is vowel or # not if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'): if (vowel == None): vowel = Node(x); start = vowel; else: vowel.next = Node(x); vowel = vowel.next; else: if (consonant == None): consonant = Node(x); end = consonant; else: consonant.next = Node(x); consonant = consonant.next; head = head.next; # In case when there is no vowel in the incoming LL # then we have to return the head of the consonant LL if (start == None): return end; # Connecting the vowel and consonant LL vowel.next = end; return start; # Driver code if __name__ == '__main__': head = None; head = append(head, 'a'); head = append(head, 'b'); head = append(head, 'c'); head = append(head, 'e'); head = append(head, 'd'); head = append(head, 'o'); head = append(head, 'x'); head = append(head, 'i'); print("Linked list before :"); printlist(head); head = arrange(head); print("Linked list after :"); printlist(head); # This code is contributed by Rajput-Ji
linear
linear
# Python3 program to partition a # linked list around a given value. import math # Link list Node class Node: def __init__(self, data): self.data = data self.next = None # A utility function to create a new node def newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to make a new list # (using the existing nodes) # and return head of new list. def partition(head, x): # Let us initialize start and # tail nodes of new list tail = head # Now iterate original list # and connect nodes curr = head while (curr != None): next = curr.next if (curr.data < x): # Insert node at head. curr.next = head head = curr else: # Append to the list of greater values # Insert node at tail. tail.next = curr tail = curr curr = next tail.next = None # The head has changed, so we need # to return it to the user. return head # Function to print linked list def printList(head): temp = head while (temp != None): print(temp.data, end = " ") temp = temp.next # Driver Code if __name__=='__main__': # Start with the empty list head = newNode(3) head.next = newNode(5) head.next.next = newNode(8) head.next.next.next = newNode(2) head.next.next.next.next = newNode(10) head.next.next.next.next.next = newNode(2) head.next.next.next.next.next.next = newNode(1) x = 5 head = partition(head, x) printList(head) # This code is contributed by AbhiThakur
constant
linear
# Python3 implementation to modify the contents # of the linked list # Linked list node class Node: def __init__(self, data): self.data = data self.next = None # Function to insert a node at the beginning # of the linked list def push(head_ref, new_data): # allocate node new_node =Node(0) # put in the data new_node.data = new_data # link the old list at the end #of the new node new_node.next = head_ref # move the head to point to the new node head_ref = new_node return head_ref front = None back = None # Split the nodes of the given list # into front and back halves, # and return the two lists # using the reference parameters. # Uses the fast/slow pointer strategy. def frontAndBackSplit( head): global front global back slow = None fast = None slow = head fast = head.next # Advance 'fast' two nodes, and # advance 'slow' one node while (fast != None): fast = fast.next if (fast != None): slow = slow.next fast = fast.next # 'slow' is before the midpoint in the list, # so split it in two at that point. front = head back = slow.next slow.next = None return head # Function to reverse the linked list def reverseList( head_ref): current = None prev = None next = None current = head_ref prev = None while (current != None): next = current.next current.next = prev prev = current current = next head_ref = prev return head_ref # perform the required subtraction operation # on the 1st half of the linked list def modifyTheContentsOf1stHalf(): global front global back front1 = front back1 = back # traversing both the lists simultaneously while (back1 != None): # subtraction operation and node data # modification front1.data = front1.data - back1.data front1 = front1.next back1 = back1.next # function to concatenate the 2nd(back) list # at the end of the 1st(front) list and # returns the head of the new list def concatFrontAndBackList( front, back): head = front if(front == None): return back while (front.next != None): front = front.next front.next = back return head # function to modify the contents of the linked list def modifyTheList( head): global front global back # if list is empty or contains only single node if (head == None or head.next == None): return head front = None back = None # split the list into two halves # front and back lists frontAndBackSplit(head) # reverse the 2nd(back) list back = reverseList(back) # modify the contents of 1st half modifyTheContentsOf1stHalf() # agains reverse the 2nd(back) list back = reverseList(back) # concatenating the 2nd list back to the # end of the 1st list head = concatFrontAndBackList(front, back) # pointer to the modified list return head # function to print the linked list def printList( head): if (head == None): return while (head.next != None): print(head.data , " -> ",end="") head = head.next print(head.data ) # Driver Code head = None # creating the linked list head = push(head, 10) head = push(head, 7) head = push(head, 12) head = push(head, 8) head = push(head, 9) head = push(head, 2) # modify the linked list head = modifyTheList(head) # print the modified linked list print( "Modified List:" ) printList(head) # This code is contributed by Arnab Kundu
constant
linear
# Python3 implementation to modify the # contents of the linked list # Linked list node class Node: def __init__(self): self.data = 0 self.next = None # Function to insert a node at the # beginning of the linked list def append(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data # Link the old list at the end # of the new node new_node.next = head_ref # Move the head to point to the new node head_ref = new_node return head_ref # Function to print the linked list def printList(head): if (not head): return; while (head.next != None): print(head.data, end = ' -> ') head = head.next print(head.data) # Function to middle node of list. def find_mid(head): temp = head slow = head fast = head while (fast and fast.next): # Advance 'fast' two nodes, and # advance 'slow' one node slow = slow.next fast = fast.next.next # If number of nodes are odd then # update slow by slow.next; if (fast): slow = slow.next return slow # Function to modify the contents of # the linked list. def modifyTheList(head, slow): # Create Stack. s = [] temp = head while (slow): s.append(slow.data) slow = slow.next # Traverse the list by using # temp until stack is empty. while (len(s) != 0): temp.data = temp.data - s[-1] temp = temp.next s.pop() # Driver code if __name__=='__main__': head = None # creating the linked list head = append(head, 10) head = append(head, 7) head = append(head, 12) head = append(head, 8) head = append(head, 9) head = append(head, 2) # Call Function to Find the # starting point of second half of list. mid = find_mid(head) # Call function to modify the # contents of the linked list. modifyTheList( head, mid) # Print the modified linked list print("Modified List:") printList(head) # This code is contributed by rutvik_56
linear
linear
# Python3 program to rotate a matrix by 90 degrees N = 4 # An Inplace function to rotate # N x N matrix by 90 degrees in # anti-clockwise direction def rotateMatrix(mat): # Consider all squares one by one for x in range(0, int(N / 2)): # Consider elements in group # of 4 in current square for y in range(x, N-x-1): # store current cell in temp variable temp = mat[x][y] # move values from right to top mat[x][y] = mat[y][N-1-x] # move values from bottom to right mat[y][N-1-x] = mat[N-1-x][N-1-y] # move values from left to bottom mat[N-1-x][N-1-y] = mat[N-1-y][x] # assign temp to left mat[N-1-y][x] = temp # Function to print the matrix def displayMatrix(mat): for i in range(0, N): for j in range(0, N): print(mat[i][j], end=' ') print("") # Driver Code if __name__ == "__main__": mat = [[0 for x in range(N)] for y in range(N)] mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function call rotateMatrix(mat) # Print rotated matrix displayMatrix(mat) # This code is contributed by saloni1297
constant
quadratic
# Python program to rotate # a matrix by 90 degrees def rotateMatrix(mat): # reversing the matrix for i in range(len(mat)): mat[i].reverse() # make transpose of the matrix for i in range(len(mat)): for j in range(i, len(mat)): # swapping mat[i][j] and mat[j][i] mat[i][j], mat[j][i] = mat[j][i], mat[i][j] # Function to print the matrix def displayMatrix(mat): for i in range(0, len(mat)): for j in range(0, len(mat)): print(mat[i][j], end=' ') print() # Driver code if __name__ == "__main__": mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function call rotateMatrix(mat) # Print rotated matrix displayMatrix(mat) # This code is contributed by shivambhagat02(CC).
constant
quadratic
# Python3 program to # rotate a matrix by # 180 degrees N = 3; # Function to Rotate # the matrix by 180 degree def rotateMatrix(mat): # Simply print from # last cell to first cell. i = N - 1; while(i >= 0): j = N - 1; while(j >= 0): print(mat[i][j], end = " "); j = j - 1; print(); i = i - 1; # Driven code mat = [[1, 2, 3], [ 4, 5, 6 ], [ 7, 8, 9 ]]; rotateMatrix(mat); # This code is contributed # by mits
constant
quadratic
# Python3 program for left rotation of matrix by 180 R = 4 C = 4 # Function to rotate the matrix by 180 degree def reverseColumns(arr): for i in range(C): j = 0 k = C-1 while j < k: t = arr[j][i] arr[j][i] = arr[k][i] arr[k][i] = t j += 1 k -= 1 # Function for transpose of matrix def transpose(arr): for i in range(R): for j in range(i, C): t = arr[i][j] arr[i][j] = arr[j][i] arr[j][i] = t # Function for display the matrix def printMatrix(arr): for i in range(R): for j in range(C): print(arr[i][j], end = " "); print(); # Function to anticlockwise rotate matrix # by 180 degree def rotate180(arr): transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); # Driven code arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [9, 10, 11, 12 ], [13, 14, 15, 16 ] ]; rotate180(arr); printMatrix(arr);
constant
quadratic
# Reverse Row at specified index in the matrix def reverseRow(data, index): cols = len(data[index]) for i in range(cols // 2): temp = data[index][i] data[index][i] = data[index][cols - i - 1] data[index][cols - i - 1] = temp return data # Print Matrix data def printMatrix(data): for i in range(len(data)): for j in range(len(data[0])): print(data[i][j], end = ' ') print() # Rotate Matrix by 180 degrees def rotateMatrix(data): rows = len(data) cols = len(data[0]) if (rows % 2): # If N is odd reverse the middle # row in the matrix data = reverseRow(data, len(data) // 2) # Swap the value of matrix [i][j] with # [rows - i - 1][cols - j - 1] for half # the rows size. for i in range(rows // 2): for j in range(cols): temp = data[i][j] data[i][j] = data[rows - i - 1][cols - j - 1] data[rows - i - 1][cols - j - 1] = temp return data # Driver Code data = [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 10 ], [ 11, 12, 13, 14, 15 ], [ 16, 17, 18, 19, 20 ], [ 21, 22, 23, 24, 25 ] ] # Rotate Matrix data = rotateMatrix(data) # Print Matrix printMatrix(data) # This code is contributed by rohitsingh07052
constant
quadratic
# Python3 program to check if all rows # of a matrix are rotations of each other MAX = 1000 # Returns true if all rows of mat[0..n-1][0..n-1] # are rotations of each other. def isPermutedMatrix(mat, n) : # Creating a string that contains # elements of first row. str_cat = "" for i in range(n) : str_cat = str_cat + "-" + str(mat[0][i]) # Concatenating the string with itself # so that substring search operations # can be performed on this str_cat = str_cat + str_cat # Start traversing remaining rows for i in range(1, n) : # Store the matrix into vector # in the form of strings curr_str = "" for j in range(n) : curr_str = curr_str + "-" + str(mat[i][j]) # Check if the current string is present # in the concatenated string or not if (str_cat.find(curr_str)) : return True return False # Driver code if __name__ == "__main__" : n = 4 mat = [[1, 2, 3, 4], [4, 1, 2, 3], [3, 4, 1, 2], [2, 3, 4, 1]] if (isPermutedMatrix(mat, n)): print("Yes") else : print("No") # This code is contributed by Ryuga
linear
cubic
# Python3 implementation to sort # the given matrix SIZE = 10 # Function to sort the given matrix def sortMat(mat, n) : # Temporary matrix of size n^2 temp = [0] * (n * n) k = 0 # Copy the elements of matrix # one by one into temp[] for i in range(0, n) : for j in range(0, n) : temp[k] = mat[i][j] k += 1 # sort temp[] temp.sort() # copy the elements of temp[] # one by one in mat[][] k = 0 for i in range(0, n) : for j in range(0, n) : mat[i][j] = temp[k] k += 1 # Function to print the given matrix def printMat(mat, n) : for i in range(0, n) : for j in range( 0, n ) : print(mat[i][j] , end = " ") print() # Driver program to test above mat = [ [ 5, 4, 7 ], [ 1, 3, 8 ], [ 2, 9, 6 ] ] n = 3 print( "Original Matrix:") printMat(mat, n) sortMat(mat, n) print("\nMatrix After Sorting:") printMat(mat, n) # This code is contributed by Nikita Tiwari.
quadratic
quadratic
# Python program to find median of matrix # sorted row wise from bisect import bisect_right as upper_bound MAX = 100; # Function to find median in the matrix def binaryMedian(m, r, d): mi = m[0][0] mx = 0 for i in range(r): if m[i][0] < mi: mi = m[i][0] if m[i][d-1] > mx : mx = m[i][d-1] desired = (r * d + 1) // 2 while (mi < mx): mid = mi + (mx - mi) // 2 place = [0]; # Find count of elements smaller than or equal to mid for i in range(r): j = upper_bound(m[i], mid) place[0] = place[0] + j if place[0] < desired: mi = mid + 1 else: mx = mid print ("Median is", mi) return # Driver code r, d = 3, 3 m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]] binaryMedian(m, r, d) # This code is contributed by Sachin BIsht
constant
nlogn
# Recursive code for Matrix Multiplication MAX = 100 i = 0 j = 0 k = 0 def multiplyMatrixRec(row1, col1, A, row2, col2, B, C): # Note that below variables are static # i and j are used to know current cell of # result matrix C[][]. k is used to know # current column number of A[][] and row # number of B[][] to be multiplied global i global j global k # If all rows traversed. if (i >= row1): return # If i < row1 if (j < col2): if (k < col1): C[i][j] += A[i][k] * B[k][j] k += 1 multiplyMatrixRec(row1, col1, A, row2, col2,B, C) k = 0 j += 1 multiplyMatrixRec(row1, col1, A, row2, col2, B, C) j = 0 i += 1 multiplyMatrixRec(row1, col1, A, row2, col2, B, C) # Function to multiply two matrices # A[][] and B[][] def multiplyMatrix(row1, col1, A, row2, col2, B): if (row2 != col1): print("Not Possible") return C = [[0 for i in range(MAX)] for i in range(MAX)] multiplyMatrixRec(row1, col1, A, row2, col2, B, C) # Print the result for i in range(row1): for j in range(col2): print( C[i][j], end = " ") print() # Driver Code A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] row1 = 3 col1 = 3 row2 = 3 col2 = 3 multiplyMatrix(row1, col1, A, row2, col2, B) # This code is contributed by sahilshelangia
logn
quadratic
# Python3 program to print Lower # triangular and Upper triangular # matrix of an array # Function to form lower triangular # matrix def lower(matrix, row, col): for i in range(0, row): for j in range(0, col): if (i < j): print("0", end = " "); else: print(matrix[i][j], end = " " ); print(" "); # Function to form upper triangular matrix def upper(matrix, row, col): for i in range(0, row): for j in range(0, col): if (i > j): print("0", end = " "); else: print(matrix[i][j], end = " " ); print(" "); # Driver Code matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; row = 3; col = 3; print("Lower triangular matrix: "); lower(matrix, row, col); print("Upper triangular matrix: "); upper(matrix, row, col); # This code is contributed by # Shivi_Aggarwal
constant
quadratic
# python3 program for the above approach def spiralOrder(matrix): ans = [] if (len(matrix) == 0): return ans m = len(matrix) n = len(matrix[0]) seen = [[0 for i in range(n)] for j in range(m)] dr = [0, 1, 0, -1] dc = [1, 0, -1, 0] x = 0 y = 0 di = 0 # Iterate from 0 to R * C - 1 for i in range(m * n): ans.append(matrix[x][y]) seen[x][y] = True cr = x + dr[di] cc = y + dc[di] if (0 <= cr and cr < m and 0 <= cc and cc < n and not(seen[cr][cc])): x = cr y = cc else: di = (di + 1) % 4 x += dr[di] y += dc[di] return ans # Driver code if __name__ == "__main__": a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function call for x in spiralOrder(a): print(x, end=" ") print()
linear
linear
# Python3 program to print # given matrix in spiral form def spiralPrint(m, n, a): k = 0 l = 0 ''' k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ''' while (k < m and l < n): # Print the first row from # the remaining rows for i in range(l, n): print(a[k][i], end=" ") k += 1 # Print the last column from # the remaining columns for i in range(k, m): print(a[i][n - 1], end=" ") n -= 1 # Print the last row from # the remaining rows if (k < m): for i in range(n - 1, (l - 1), -1): print(a[m - 1][i], end=" ") m -= 1 # Print the first column from # the remaining columns if (l < n): for i in range(m - 1, k - 1, -1): print(a[i][l], end=" ") l += 1 # Driver Code a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] R = 4 C = 4 # Function Call spiralPrint(R, C, a) # This code is contributed by Nikita Tiwari.
constant
quadratic
# Python3 program for the above approach # Function for printing matrix in spiral # form i, j: Start index of matrix, row # and column respectively m, n: End index # of matrix row and column respectively def printdata(arr, i, j, m, n): # If i or j lies outside the matrix if (i >= m or j >= n): return # Print First Row for p in range(i, n): print(arr[i][p], end=" ") # Print Last Column for p in range(i + 1, m): print(arr[p][n - 1], end=" ") # Print Last Row, if Last and # First Row are not same if ((m - 1) != i): for p in range(n - 2, j - 1, -1): print(arr[m - 1][p], end=" ") # Print First Column, if Last and # First Column are not same if ((n - 1) != j): for p in range(m - 2, i, -1): print(arr[p][j], end=" ") printdata(arr, i + 1, j + 1, m - 1, n - 1) # Driver code if __name__ == "__main__": R = 4 C = 4 arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function Call printdata(arr, 0, 0, R, C) # This code is contributed by avsadityavardhan
constant
quadratic
# Python3 program for the above approach R = 4 C = 4 def isInBounds(i, j): global R global C if (i < 0 or i >= R or j < 0 or j >= C): return False return True # Check if the position is blocked def isBlocked(matrix, i, j): if (not isInBounds(i, j)): return True if (matrix[i][j] == -1): return True return False # DFS code to traverse spirally def spirallyDFSTravserse(matrix, i, j, Dir, res): if (isBlocked(matrix, i, j)): return allBlocked = True for k in range(-1, 2, 2): allBlocked = allBlocked and isBlocked( matrix, k + i, j) and isBlocked(matrix, i, j + k) res.append(matrix[i][j]) matrix[i][j] = -1 if (allBlocked): return # dir: 0 - right, 1 - down, 2 - left, 3 - up nxt_i = i nxt_j = j nxt_dir = Dir if (Dir == 0): if (not isBlocked(matrix, i, j + 1)): nxt_j += 1 else: nxt_dir = 1 nxt_i += 1 elif(Dir == 1): if (not isBlocked(matrix, i + 1, j)): nxt_i += 1 else: nxt_dir = 2 nxt_j -= 1 elif(Dir == 2): if (not isBlocked(matrix, i, j - 1)): nxt_j -= 1 else: nxt_dir = 3 nxt_i -= 1 elif(Dir == 3): if (not isBlocked(matrix, i - 1, j)): nxt_i -= 1 else: nxt_dir = 0 nxt_j += 1 spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res) # To traverse spirally def spirallyTraverse(matrix): res = [] spirallyDFSTravserse(matrix, 0, 0, 0, res) return res # Driver code if __name__ == "__main__": a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function Call res = spirallyTraverse(a) print(*res) # This code is contributed by rag2127
constant
quadratic
# Python program to find unique element in matrix # function that calculate unique element def unique(mat, r, c) -> int: # declare map for hashing mp = {} for i in range(r): for j in range(c): # increase freq of mat[i][j] in map if mat[i][j] not in mp: mp[mat[i][j]] = 1 else: mp[mat[i][j]] += 1 flag = False # print unique element for p in mp: if mp[p] == 1: print(p, end=" ") flag = True if flag == False: print("No unique element in the matrix") # Driver program if __name__ == "__main__": mat = [[1, 2, 3, 20], [5, 6, 20, 25], [1, 3, 5, 6], [6, 7, 8, 15]] # function that calculate unique element unique(mat, 4, 4) # This code is contributed by ajaymakvana
quadratic
quadratic
# Python3 program to shift k # elements in a matrix. N = 4 # Function to shift first k # elements of each row of # matrix. def shiftMatrixByK(mat, k): if (k > N) : print ("shifting is" " not possible") return j = 0 while (j < N) : # Print elements from # index k for i in range(k, N): print ("{} " . format(mat[j][i]), end="") # Print elements before # index k for i in range(0, k): print ("{} " . format(mat[j][i]), end="") print ("") j = j + 1 # Driver code mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] k = 2 # Function call shiftMatrixByK(mat, k) # This code is contributed by # Manish Shaw (manishshaw1)
constant
quadratic
# Python3 Program to swap diagonal of a matrix # size of square matrix N = 3 # Function to swap diagonal of matrix def swapDiagonal(matrix): for i in range(N): matrix[i][i], matrix[i][N-i-1] = \ matrix[i][N-i-1], matrix[i][i] # Driver Code matrix = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] # swap diagonals of matrix swapDiagonal(matrix); # Displaying modified matrix for i in range(N): for j in range(N): print(matrix[i][j], end = ' ') print()
constant
quadratic
# Python 3 program for finding max path in matrix # To calculate max path in matrix def findMaxPath(mat): for i in range(1, N): res = -1 for j in range(M): # When all paths are possible if (j > 0 and j < M - 1): mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])) # When diagonal right is not possible else if (j > 0): mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]) # When diagonal left is not possible else if (j < M - 1): mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]) # Store max path sum res = max(mat[i][j], res) return res # Driver program to check findMaxPath N=4 M=6 mat = ([[ 10, 10, 2, 0, 20, 4 ], [ 1, 0, 0, 30, 2, 5 ], [ 0, 10, 4, 0, 2, 0 ], [ 1, 0, 2, 20, 0, 4 ]]) print(findMaxPath(mat)) # This code is contributed by Azkia Anam.
constant
quadratic
# Python3 code to move matrix elements # in given direction with add # element with same value MAX = 50 # Function to shift the matrix # in the given direction def moveMatrix(d, n, a): # For right shift move. if (d[0] == 'r'): # For each row from # top to bottom for i in range(n): v = [] w = [] # For each element of # row from right to left for j in range(n - 1, -1, -1): # if not 0 if (a[i][j]): v.append(a[i][j]) # For each temporary array j = 0 while (j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each row element to 0. for j in range(n): a[i][j] = 0 j = n - 1 # Copying the temporary # array to the current row. for it in w: a[i][j] = it j -= 1 # For left shift move elif (d[0] == 'l'): # For each row for i in range(n): v = [] w = [] # For each element of the # row from left to right for j in range(n): # If not 0 if (a[i][j]): v.append(a[i][j]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each row element to 0. for j in range(n): a[i][j] = 0 j = 0 for it in w: a[i][j] = it j += 1 # For down shift move. elif (d[0] == 'd'): # For each column for i in range(n): v = [] w = [] # For each element of # column from bottom to top for j in range(n - 1, -1, -1): # If not 0 if (a[j][i]): v.append(a[j][i]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j <len( v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each column element to 0. for j in range(n): a[j][i] = 0 j = n - 1 # Copying the temporary array # to the current column for it in w: a[j][i] = it j -= 1 # For up shift move elif (d[0] == 'u'): # For each column for i in range(n): v = [] w = [] # For each element of column # from top to bottom for j in range(n): # If not 0 if (a[j][i]): v.append(a[j][i]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each column element to 0. for j in range(n): a[j][i] = 0 j = 0 # Copying the temporary array # to the current column for it in w: a[j][i] = it j += 1 # Driver Code if __name__ == "__main__": d = ["l"] * 2 n = 5 a = [ [ 32, 3, 3, 3, 3 ], [ 0, 0, 1, 0, 0 ], [ 10, 10, 8, 1, 2 ], [ 0, 0, 0, 0, 1 ], [ 4, 5, 6, 7, 8 ] ] moveMatrix(d, n, a) # Printing the final array for i in range(n): for j in range(n): print(a[i][j], end = " ") print() # This code is contributed by chitranayal
linear
quadratic
# Python implementation to sort the rows # of matrix in ascending order followed by # sorting the columns in descending order MAX_SIZE=10 # function to sort each row of the matrix # according to the order specified by # ascending. def sortByRow(mat, n, ascending): for i in range(n): if (ascending): mat[i].sort() else: mat[i].sort(reverse=True) # function to find # transpose of the matrix def transpose(mat, n): for i in range(n): for j in range(i + 1, n): # swapping element at index (i, j) # by element at index (j, i) temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp # function to sort # the matrix row-wise # and column-wise def sortMatRowAndColWise(mat, n): # sort rows of mat[][] sortByRow(mat, n, True) # get transpose of mat[][] transpose(mat, n) # again sort rows of # mat[][] in descending # order. sortByRow(mat, n, False) # again get transpose of mat[][] transpose(mat, n) # function to print the matrix def printMat(mat, n): for i in range(n): for j in range(n): print(mat[i][j] , " ", end="") print() #Driver code n = 3 mat = [[3, 2, 1], [9, 8, 7], [6, 5, 4]] print("Original Matrix:") printMat(mat, n) sortMatRowAndColWise(mat, n) print("Matrix After Sorting:") printMat(mat, n) # This code is contributed # by Anant Agarwal.
constant
quadratic
# Python program to find sum of # middle row and column in matrix def middlesum(mat,n): row_sum = 0 col_sum = 0 # loop for sum of row for i in range(n): row_sum += mat[n // 2][i] print("Sum of middle row = ", row_sum) # loop for sum of column for i in range(n): col_sum += mat[i][n // 2] print("Sum of middle column = ", col_sum) # Driver code mat= [[2, 5, 7], [3, 7, 2], [5, 6, 9]] middlesum(mat, 3) # This code is contributed # by Anant Agarwal.
constant
linear
# Python3 program showing time difference # in row major and column major access # taking MAX 10000 so that time difference # can be shown from time import clock MAX = 1000 arr = [[0 for i in range(MAX)] for i in range(MAX)] def rowMajor(): global arr # accessing element row wise for i in range(MAX): for j in range(MAX): arr[i][j] += 1 def colMajor(): global arr # accessing element column wise for i in range(MAX): for j in range(MAX): arr[j][i] += 1 # Driver code if __name__ == '__main__': # Time taken by row major order t = clock() rowMajor() t = clock() - t print("Row major access time :{:.2f} s".format(t)) # Time taken by column major order t = clock() colMajor() t = clock() - t print("Column major access time :{:.2f} s".format(t)) # This code is contributed by mohit kumar 29
quadratic
quadratic
# Python program to rotate # a matrix right by k times # size of matrix M = 3 N = 3 matrix = [[12, 23, 34], [45, 56, 67], [78, 89, 91]] # function to rotate # matrix by k times def rotateMatrix(k) : global M, N, matrix # temporary array # of size M temp = [0] * M # within the size # of matrix k = k % M for i in range(0, N) : # copy first M-k elements # to temporary array for t in range(0, M - k) : temp[t] = matrix[i][t] # copy the elements from # k to end to starting for j in range(M - k, M) : matrix[i][j - M + k] = matrix[i][j] # copy elements from # temporary array to end for j in range(k, M) : matrix[i][j] = temp[j - k] # function to display # the matrix def displayMatrix() : global M, N, matrix for i in range(0, N) : for j in range(0, M) : print ("{} " . format(matrix[i][j]), end = "") print () # Driver code k = 2 # rotate matrix by k rotateMatrix(k) # display rotated matrix displayMatrix() # This code is contributed by # Manish Shaw(manishshaw1)
linear
quadratic
# Python Program to check given matrix # is idempotent matrix or not. import math # Function for matrix multiplication. def multiply(mat, res): N= len(mat) for i in range(0,N): for j in range(0,N): res[i][j] = 0 for k in range(0,N): res[i][j] += mat[i][k] * mat[k][j] # Function to check idempotent # property of matrix. def checkIdempotent(mat): N= len(mat) # Calculate multiplication of matrix # with itself and store it into res. res =[[0]*N for i in range(0,N)] multiply(mat, res) for i in range(0,N): for j in range(0,N): if (mat[i][j] != res[i][j]): return False return True # driver Function mat = [ [2, -2, -4], [-1, 3, 4], [1, -2, -3] ] # checkIdempotent function call. if (checkIdempotent(mat)): print("Idempotent Matrix") else: print("Not Idempotent Matrix.") # This code is contributed by Gitanjali.
quadratic
cubic
# Program to implement involutory matrix. N = 3; # Function for matrix multiplication. def multiply(mat, res): for i in range(N): for j in range(N): res[i][j] = 0; for k in range(N): res[i][j] += mat[i][k] * mat[k][j]; return res; # Function to check involutory matrix. def InvolutoryMatrix(mat): res=[[0 for i in range(N)] for j in range(N)]; # multiply function call. res = multiply(mat, res); for i in range(N): for j in range(N): if (i == j and res[i][j] != 1): return False; if (i != j and res[i][j] != 0): return False; return True; # Driver Code mat = [[1, 0, 0], [0, -1, 0], [0, 0, -1]]; # Function call. If function # return true then if part # will execute otherwise # else part will execute. if (InvolutoryMatrix(mat)): print("Involutory Matrix"); else: print("Not Involutory Matrix"); # This code is contributed by mits
quadratic
cubic
# Python3 code to swap the element # of first and last row and display # the result def interchangeFirstLast(mat, n, m): rows = n # swapping of element between # first and last rows for i in range(n): t = mat[0][i] mat[0][i] = mat[rows-1][i] mat[rows-1][i] = t # Driver code if __name__ == "__main__": mat = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]] n = 4 m = 4 # Function call interchangeFirstLast(mat, n, m) # printing the interchanged matrix for i in range(n): for j in range(m): print(mat[i][j], end=" ") print("\n") # This code is contributed by Shrikant13.
constant
linear
# Python3 code to sort 2D matrix row-wise def sortRowWise(m): # loop for rows of matrix for i in range(len(m)): # loop for column of matrix for j in range(len(m[i])): # loop for comparison and swapping for k in range(len(m[i]) - j - 1): if (m[i][k] > m[i][k + 1]): # swapping of elements t = m[i][k] m[i][k] = m[i][k + 1] m[i][k + 1] = t # printing the sorted matrix for i in range(len(m)): for j in range(len(m[i])): print(m[i][j], end=" ") print() # Driver code m = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2],[ 6, 3, 1, 2 ]] sortRowWise(m) # This code is contributed by shubhamsingh10
constant
quadratic
# Python3 code to sort 2D matrix row-wise def sortRowWise(m): # One by one sort individual rows. for i in range(len(m)): m[i].sort() # printing the sorted matrix for i in range(len(m)): for j in range(len(m[i])): print(m[i][j], end=" ") print() return 0 # Driver code m = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2 ],[ 6, 3, 1, 2]] sortRowWise(m) # This code is contributed by shubhamsingh10
constant
quadratic
# Python 3 code to check Markov Matrix def checkMarkov(m) : # Outer loop to access rows # and inner to access columns for i in range(0, len(m)) : # Find sum of current row sm = 0 for j in range(0, len(m[i])) : sm = sm + m[i][j] if (sm != 1) : return False return True # Matrix to check m = [ [ 0, 0, 1 ], [ 0.5, 0, 0.5 ], [ 1, 0, 0 ] ] # Calls the function check() if (checkMarkov(m)) : print(" yes ") else : print(" no ") # This code is contributed by Nikita Tiwari.
constant
quadratic
# Python3 Program to check if matrix # is diagonal matrix or not. N = 4 # Function to check matrix # is diagonal matrix # or not. def isDiagonalMatrix(mat) : for i in range(0, N): for j in range(0, N) : # condition to check # other elements # except main diagonal # are zero or not. if ((i != j) and (mat[i][j] != 0)) : return False return True # Driver function mat = [[ 4, 0, 0, 0 ], [ 0, 7, 0, 0 ], [ 0, 0, 5, 0 ], [ 0, 0, 0, 1 ]] if (isDiagonalMatrix(mat)) : print("Yes") else : print("No") # This code is contributed by Nikita Tiwari.
constant
quadratic
# Program to check matrix # is scalar matrix or not. N = 4 # Function to check matrix is # scalar matrix or not. def isScalarMatrix(mat) : # Check all elements # except main diagonal are # zero or not. for i in range(0,N) : for j in range(0,N) : if ((i != j) and (mat[i][j] != 0)) : return False # Check all diagonal # elements are same or not. for i in range(0,N-1) : if (mat[i][i] != mat[i + 1][i + 1]) : return False return True # Driver function mat = [[ 2, 0, 0, 0 ], [ 0, 2, 0, 0 ], [ 0, 0, 2, 0 ], [ 0, 0, 0, 2 ]] # Function call if (isScalarMatrix(mat)): print("Yes") else : print("No") # This code is contributed by # Nikita tiwari.
constant
quadratic
# Python 3 implementation to # sort the matrix row-wise # and column-wise MAX_SIZE = 10 # function to sort each # row of the matrix def sortByRow(mat, n): for i in range (n): # sorting row number 'i' for j in range(n-1): if mat[i][j] > mat[i][j + 1]: temp = mat[i][j] mat[i][j] = mat[i][j + 1] mat[i][j + 1] = temp # function to find # transpose of the matrix def transpose(mat, n): for i in range (n): for j in range(i + 1, n): # swapping element at # index (i, j) by element # at index (j, i) t = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = t # function to sort # the matrix row-wise # and column-wise def sortMatRowAndColWise(mat, n): # sort rows of mat[][] sortByRow(mat, n) # get transpose of mat[][] transpose(mat, n) # again sort rows of mat[][] sortByRow(mat, n) # again get transpose of mat[][] transpose(mat, n) # function to print the matrix def printMat(mat, n): for i in range(n): for j in range(n): print(str(mat[i][j] ), end = " ") print(); # Driver Code mat = [[ 4, 1, 3 ], [ 9, 6, 8 ], [ 5, 2, 7 ]] n = 3 print("Original Matrix:") printMat(mat, n) sortMatRowAndColWise(mat, n) print("\nMatrix After Sorting:") printMat(mat, n) # This code is contributed # by ChitraNayal
constant
quadratic
# Program to count islands in boolean 2D matrix class Graph: def __init__(self, row, col, g): self.ROW = row self.COL = col self.graph = g # A function to check if a given cell # (row, col) can be included in DFS def isSafe(self, i, j, visited): # row number is in range, column number # is in range and value is 1 # and not yet visited return (i >= 0 and i < self.ROW and j >= 0 and j < self.COL and not visited[i][j] and self.graph[i][j]) # A utility function to do DFS for a 2D # boolean matrix. It only considers # the 8 neighbours as adjacent vertices def DFS(self, i, j, visited): # These arrays are used to get row and # column numbers of 8 neighbours # of a given cell rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] # Mark this cell as visited visited[i][j] = True # Recur for all connected neighbours for k in range(8): if self.isSafe(i + rowNbr[k], j + colNbr[k], visited): self.DFS(i + rowNbr[k], j + colNbr[k], visited) # The main function that returns # count of islands in a given boolean # 2D matrix def countIslands(self): # Make a bool array to mark visited cells. # Initially all cells are unvisited visited = [[False for j in range(self.COL)]for i in range(self.ROW)] # Initialize count as 0 and traverse # through the all cells of # given matrix count = 0 for i in range(self.ROW): for j in range(self.COL): # If a cell with value 1 is not visited yet, # then new island found if visited[i][j] == False and self.graph[i][j] == 1: # Visit all cells in this island # and increment island count self.DFS(i, j, visited) count += 1 return count graph = [[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]] row = len(graph) col = len(graph[0]) g = Graph(row, col, graph) print("Number of islands is:") print(g.countIslands()) # This code is contributed by Neelam Yadav
quadratic
quadratic
# Program to count islands in boolean 2D matrix class Graph: def __init__(self, row, col, graph): self.ROW = row self.COL = col self.graph = graph # A utility function to do DFS for a 2D # boolean matrix. It only considers # the 8 neighbours as adjacent vertices def DFS(self, i, j): if i < 0 or i >= len(self.graph) or j < 0 or j >= len(self.graph[0]) or self.graph[i][j] != 1: return # mark it as visited self.graph[i][j] = -1 # Recur for 8 neighbours self.DFS(i - 1, j - 1) self.DFS(i - 1, j) self.DFS(i - 1, j + 1) self.DFS(i, j - 1) self.DFS(i, j + 1) self.DFS(i + 1, j - 1) self.DFS(i + 1, j) self.DFS(i + 1, j + 1) # The main function that returns # count of islands in a given boolean # 2D matrix def countIslands(self): # Initialize count as 0 and traverse # through the all cells of # given matrix count = 0 for i in range(self.ROW): for j in range(self.COL): # If a cell with value 1 is not visited yet, # then new island found if self.graph[i][j] == 1: # Visit all cells in this island # and increment island count self.DFS(i, j) count += 1 return count graph = [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1] ] row = len(graph) col = len(graph[0]) g = Graph(row, col, graph) print("Number of islands is:", g.countIslands()) # This code is contributed by Shivam Shrey
quadratic
quadratic
# Python program to print magic square of double order def DoublyEven(n): # 2-D matrix with all entries as 0 arr = [[(n*y)+x+1 for x in range(n)]for y in range(n)] # Change value of array elements at fix location # as per the rule (n*n+1)-arr[i][[j] # Corners of order (n/4)*(n/4) # Top left corner for i in range(0,n//4): for j in range(0,n//4): arr[i][j] = (n*n + 1) - arr[i][j]; # Top right corner for i in range(0,n//4): for j in range(3 * (n//4),n): arr[i][j] = (n*n + 1) - arr[i][j]; # Bottom Left corner for i in range(3 * (n//4),n): for j in range(0,n//4): arr[i][j] = (n*n + 1) - arr[i][j]; # Bottom Right corner for i in range(3 * (n//4),n): for j in range(3 * (n//4),n): arr[i][j] = (n*n + 1) - arr[i][j]; # Centre of matrix,order (n/2)*(n/2) for i in range(n//4,3 * (n//4)): for j in range(n//4,3 * (n//4)): arr[i][j] = (n*n + 1) - arr[i][j]; # Printing the square for i in range(n): for j in range(n): print ('%2d ' %(arr[i][j]),end=" ") print() # Driver Program n = 8 DoublyEven(n) # Contributed by Harshit Agrawal
quadratic
quadratic
# Python program to generate # odd sized magic squares # A function to generate odd # sized magic squares def generateSquare(n): # 2-D array with all # slots set to 0 magicSquare = [[0 for x in range(n)] for y in range(n)] # initialize position of 1 i = n // 2 j = n - 1 # Fill the magic square # by placing values num = 1 while num <= (n * n): if i == -1 and j == n: # 3rd condition j = n - 2 i = 0 else: # next number goes out of # right side of square if j == n: j = 0 # next number goes # out of upper side if i < 0: i = n - 1 if magicSquare[int(i)][int(j)]: # 2nd condition j = j - 2 i = i + 1 continue else: magicSquare[int(i)][int(j)] = num num = num + 1 j = j + 1 i = i - 1 # 1st condition # Printing magic square print("Magic Square for n =", n) print("Sum of each row or column", n * (n * n + 1) // 2, "\n") for i in range(0, n): for j in range(0, n): print('%2d ' % (magicSquare[i][j]), end='') # To display output # in matrix form if j == n - 1: print() # Driver Code # Works only when n is odd n = 7 generateSquare(n) # This code is contributed # by Harshit Agrawal
quadratic
quadratic
# Python3 program to check whether a given # matrix is magic matrix or not # Returns true if mat[][] is magic # square, else returns false. def isMagicSquare( mat) : n = len(mat) # sumd1 and sumd2 are the sum of the two diagonals sumd1=0 sumd2=0 for i in range(n): # (i, i) is the diagonal from top-left -> bottom-right # (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1+=mat[i][i] sumd2+=mat[i][n-i-1] # if the two diagonal sums are unequal then it is not a magic square if not(sumd1==sumd2): return False for i in range(n): #sumr is rowsum and sumc is colsum sumr=0 sumc=0 for j in range(n): sumr+=mat[i][j] sumc+=mat[j][i] if not(sumr==sumc==sumd1): return False #if all the conditions are satisfied then it is a magic square return True # Driver Code mat = [ [ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ] ] if (isMagicSquare(mat)) : print( "Magic Square") else : print( "Not a magic Square")
constant
quadratic
# Python3 program to check whether a given # matrix is magic matrix or not # Returns true if mat[][] is magic # square, else returns false. def isMagicSquare( mat) : n = len(mat) # sumd1 and sumd2 are the sum of the two diagonals sumd1=0 sumd2=0 for i in range(n): # (i, i) is the diagonal from top-left -> bottom-right # (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1+=mat[i][i] sumd2+=mat[i][n-i-1] # if the two diagonal sums are unequal then it is not a magic square if not(sumd1==sumd2): return False for i in range(n): #sumr is rowsum and sumc is colsum sumr=0 sumc=0 for j in range(n): sumr+=mat[i][j] sumc+=mat[j][i] if not(sumr==sumc==sumd1): return False #if all the conditions are satisfied then it is a magic square return True # Driver Code mat = [ [ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ] ] if (isMagicSquare(mat)) : print( "Magic Square") else : print( "Not a magic Square")
constant
quadratic
# Python implementation to # count sub-matrices having # sum divisible by the # value 'k' # function to count all # sub-arrays divisible by k def subCount(arr, n, k) : # create auxiliary hash # array to count frequency # of remainders mod = [0] * k; # Traverse original array # and compute cumulative # sum take remainder of # this current cumulative # sum and increase count # by 1 for this remainder # in mod array cumSum = 0; for i in range(0, n) : cumSum = cumSum + arr[i]; # as the sum can be # negative, taking # modulo twice mod[((cumSum % k) + k) % k] = mod[ ((cumSum % k) + k) % k] + 1; result = 0; # Initialize result # Traverse mod for i in range(0, k) : # If there are more than # one prefix subarrays # with a particular mod value. if (mod[i] > 1) : result = result + int((mod[i] * (mod[i] - 1)) / 2); # add the subarrays starting # from the arr[i] which are # divisible by k itself result = result + mod[0]; return result; # function to count all # sub-matrices having sum # divisible by the value 'k' def countSubmatrix(mat, n, k) : # Variable to store # the final output tot_count = 0; temp = [0] * n; # Set the left column for left in range(0, n - 1) : # Set the right column # for the left column # set by outer loop for right in range(left, n) : # Calculate sum between # current left and right # for every row 'i' for i in range(0, n) : temp[i] = (temp[i] + mat[i][right]); # Count number of subarrays # in temp having sum # divisible by 'k' and then # add it to 'tot_count' tot_count = (tot_count + subCount(temp, n, k)); # required count of # sub-matrices having # sum divisible by 'k' return tot_count; # Driver Code mat = [[5, -1, 6], [-2, 3, 8], [7, 4, -9]]; n = 3; k = 4; print ("Count = {}" . format( countSubmatrix(mat, n, k))); # This code is contributed by # Manish Shaw(manishshaw1)
linear
cubic
# Python Program to check # whether given matrix is # Diagonally Dominant Matrix. # check the given # matrix is Diagonally # Dominant Matrix or not. def isDDM(m, n) : # for each row for i in range(0, n) : # for each column, finding # sum of each row. sum = 0 for j in range(0, n) : sum = sum + abs(m[i][j]) # removing the # diagonal element. sum = sum - abs(m[i][i]) # checking if diagonal # element is less than # sum of non-diagonal # element. if (abs(m[i][i]) < sum) : return False return True # Driver Code n = 3 m = [[ 3, -2, 1 ], [ 1, -3, 2 ], [ -1, 2, 4 ]] if((isDDM(m, n))) : print ("YES") else : print ("NO") # This code is contributed by # Manish Shaw(manishshaw1)
constant
quadratic
# Python 3 Program to Find minimum # number of operation required such # that sum of elements on each row # and column becomes same # Function to find minimum operation # required to make sum of each row # and column equals def findMinOpeartion(matrix, n): # Initialize the sumRow[] and sumCol[] # array to 0 sumRow = [0] * n sumCol = [0] * n # Calculate sumRow[] and sumCol[] array for i in range(n): for j in range(n): sumRow[i] += matrix[i][j] sumCol[j] += matrix[i][j] # Find maximum sum value in # either row or in column maxSum = 0 for i in range(n): maxSum = max(maxSum, sumRow[i]) maxSum = max(maxSum, sumCol[i]) count = 0 i = 0 j = 0 while i < n and j < n: # Find minimum increment required # in either row or column diff = min(maxSum - sumRow[i], maxSum - sumCol[j]) # Add difference in corresponding # cell, sumRow[] and sumCol[] array matrix[i][j] += diff sumRow[i] += diff sumCol[j] += diff # Update the count variable count += diff # If ith row satisfied, increment # ith value for next iteration if (sumRow[i] == maxSum): i += 1 # If jth column satisfied, increment # jth value for next iteration if (sumCol[j] == maxSum): j += 1 return count # Utility function to print matrix def printMatrix(matrix, n): for i in range(n): for j in range(n): print(matrix[i][j], end=" ") print() # Driver code if __name__ == "__main__": matrix = [[1, 2], [3, 4]] print(findMinOpeartion(matrix, 2)) printMatrix(matrix, 2) # This code is contributed # by ChitraNayal
linear
quadratic
# Python program to find # the frequency of k # in matrix where # m(i, j)=i+j import math def find( n, k): if (n + 1 >= k): return (k - 1) else: return (2 * n + 1 - k) # Driver Code n = 4 k = 7 freq = find(n, k) if (freq < 0): print ( " element not exist") else: print(" Frequency of " , k ," is " , freq ) # This code is contributed # by Gitanjali.
constant
constant
# Python3 program to print given number of 1's, # 2's, 3's ....k's in zig-zag way. # function that prints given number of 1's, # 2's, 3's ....k's in zig-zag way. def ZigZag(rows, columns, numbers): k = 0 # two-dimensional array to store numbers. arr = [[0 for i in range(columns)] for j in range(rows)] for i in range(rows): # for even row. if (i % 2 == 0): # for each column. j = 0 while j < columns and numbers[k] > 0: # storing element. arr[i][j] = k + 1 # decrement element at # kth index. numbers[k] -= 1 # if array contains zero # then increment index to # make this next index if numbers[k] == 0: k += 1 j += 1 # for odd row. else: # for each column. j = columns-1 while j>=0 and numbers[k]>0: # storing element. arr[i][j] = k+1 # decrement element # at kth index. numbers[k] -= 1 # if array contains zero then # increment index to make this # next index. if numbers[k] == 0: k += 1 j -= 1 # printing the stored elements. for i in arr: for j in i: print(j, end =" ") print() # Driver code rows = 4; columns = 5; Numbers = [3, 4, 2, 2, 3, 1, 5] ZigZag(rows, columns, Numbers) # This code is contributed by # Rajnis09
quadratic
quadratic
# Python3 program to find out the maximum # product in the matrix which four elements # are adjacent to each other in one direction n = 5 # function to find max product def FindMaxProduct(arr, n): max = 0 # iterate the rows. for i in range(n): # iterate the columns. for j in range( n): # check the maximum product # in horizontal row. if ((j - 3) >= 0): result = (arr[i][j] * arr[i][j - 1] * arr[i][j - 2] * arr[i][j - 3]) if (max < result): max = result # check the maximum product # in vertical row. if ((i - 3) >= 0) : result = (arr[i][j] * arr[i - 1][j] * arr[i - 2][j] * arr[i - 3][j]) if (max < result): max = result # check the maximum product in # diagonal going through down - right if ((i - 3) >= 0 and (j - 3) >= 0): result = (arr[i][j] * arr[i - 1][j - 1] * arr[i - 2][j - 2] * arr[i - 3][j - 3]) if (max < result): max = result # check the maximum product in # diagonal going through up - right if ((i - 3) >= 0 and (j - 3) <= 0): result = (arr[i][j] * arr[i - 1][j + 1] * arr[i - 2][j + 2] * arr[i - 3][j + 3]) if (max < result): max = result return max # Driver code if __name__ == "__main__": # int arr[][4] = {{6, 2, 3, 4}, # {5, 4, 3, 1}, # {7, 4, 5, 6}, # {8, 3, 1, 0}}; # int arr[][5] = {{1, 2, 1, 3, 4}, # {5, 6, 3, 9, 2}, # {7, 8, 8, 1, 2}, # {1, 0, 7, 9, 3}, # {3, 0, 8, 4, 9}}; arr = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 1], [2, 3, 4, 5, 6], [7, 8, 9, 1, 0], [9, 6, 4, 2, 3]] print(FindMaxProduct(arr, n)) # This code is contributed by ita_c
constant
quadratic
# Python implementation of the above approach def maxPro(a,n,m,k): maxi = 1 mp = 1 for i in range(n): # Window Product for each row. wp = 1 for l in range(k): wp *= a[i][l] # Maximum window product for each row mp = wp for j in range(k,m): wp = wp * a[i][j] / a[i][j - k] # Global maximum # window product maxi = max( maxi, max(mp, wp)) return maxi # Driver Code n = 6 m = 5 k = 4 a=[[1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 1 ], [ 2, 3, 4, 5, 6 ], [ 7, 8, 9, 1, 0 ], [ 9, 6, 4, 2, 3 ], [ 1, 1, 2, 1, 1 ]] # Function call maxpro = maxPro(a, n, m, k) print(maxpro) # This code is contributed by ab2127
constant
quadratic
# Python3 Program to check # lower triangular matrix. # Function to check matrix # is in lower triangular def islowertriangular(M): for i in range(0, len(M)): for j in range(i + 1, len(M)): if(M[i][j] != 0): return False return True # Driver function. M = [[1,0,0,0], [1,4,0,0], [4,6,2,0], [0,4,7,6]] if islowertriangular(M): print ("Yes") else: print ("No") # This code is contributed by Anurag Rawat
constant
quadratic
# Python3 Program to check upper # triangular matrix. # Function to check matrix # is in upper triangular def isuppertriangular(M): for i in range(1, len(M)): for j in range(0, i): if(M[i][j] != 0): return False return True # Driver function. M = [[1,3,5,3], [0,4,6,2], [0,0,2,5], [0,0,0,6]] if isuppertriangular(M): print ("Yes") else: print ("No") # This code is contributed by Anurag Rawat
constant
quadratic
# Python Program to Find the frequency # of even and odd numbers in a matrix MAX=100 # Function for calculating frequency def freq(ar, m, n): even = 0 odd = 0 for i in range(m): for j in range(n): # modulo by 2 to check # even and odd if ((ar[i][j] % 2) == 0): even += 1 else: odd += 1 # print Frequency of numbers print(" Frequency of odd number =", odd) print(" Frequency of even number =", even) # Driver code m = 3 n = 3 array = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] freq(array, m, n) # This code is contributed # by Anant Agarwal.
constant
quadratic