diff --git a/Arrays/P06_SubarraysWithGivenXor.py b/Arrays/P06_SubarraysWithGivenXor.py new file mode 100644 index 0000000..6e3df53 --- /dev/null +++ b/Arrays/P06_SubarraysWithGivenXor.py @@ -0,0 +1,34 @@ +def subarrays_with_given_XOR(arr, n, m): + prefix_xor = 0 + + d = {0: 1} # initialise dictionary, d stores count 'xor values' in arr + for i in range(n): + prefix_xor ^= arr[i] + if prefix_xor in d: + d[prefix_xor] += 1 + else: + d[prefix_xor] = 1 + + # Approach : + # We know that, If A^B = C, then: A^C=B and B^C=A, + + # In this problem :- + + # val ^ givenXor = C + # givenXor ^ c = a + # val ^ c = givenXor + # So, if val and val^givenXor=C is in d, then "givenXor" is in d. + + + cnt = 0 + for val in d: + if val^m in d: + cnt += d[val] * d[val^m] + d[e] = 0 + d[val^m] = 0 + return cnt + + +arr = [4, 2, 2, 6, 4] +xor = 6 +print(subarrays_with_given_XOR(arr, len(arr), xor)) diff --git a/Linked Lists/P03_FindMiddleOfLinkedlist.py b/Linked Lists/P03_FindMiddleOfLinkedlist.py new file mode 100644 index 0000000..7faadef --- /dev/null +++ b/Linked Lists/P03_FindMiddleOfLinkedlist.py @@ -0,0 +1,35 @@ +class Node: + def __init__(self,data): + self.data=data + self.next=None + +class linked_list: + def __init__(self): + self.head=None + + def append(self, data): + temp=Node(data) + if self.head==None: + self.head=temp + else: + p=self.head + while p.next!=None: + p=p.next + p.next=temp + + def get_mid(self, head): + if head == None: + return head + slow = fast = head + while fast.next != None and fast.next.next != None: + slow = slow.next + fast = fast.next.next + return slow.data + +ll=linked_list() +ll.append(2) +ll.append(6) +ll.append(8) +ll.append(1) +ll.append(4) +print(f'Middle element : {ll.get_mid(ll.head)}') diff --git a/Trees/P07_LCAinBST.py b/Trees/P07_LCAinBST.py new file mode 100644 index 0000000..da5bf61 --- /dev/null +++ b/Trees/P07_LCAinBST.py @@ -0,0 +1,43 @@ +# Lowest Common Ancestor in Binary search tree + +class node: + def __init__(self,key): + self.key=key + self.left=None + self.right=None + +def lca(root,n1,n2): + if root is None: + return None + + if root.keyn1 and root.key>n2: + return lca(root.left,n1,n2) + + return root + +# Consider the following BST + +# 8 +# / \ +# 3 11 +# / \ / \ +# 2 6 10 13 +# / \ / +# 5 7 12 + +# Create BST +root = node(8) +l = root.left = node(3) +r = root.right = node(11) +r.left = node(10) +r.right = node(13) +r.right.left = node(12) +l.left = node(2) +l.right = node(6) +l.right.left = node(5) +l.right.right = node(7) + +print(lca(root,2,7).key) # ouputs '3'