[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n"
  },
  {
    "path": "6sense/README.md",
    "content": "# Hackerrank Test (Personal Experience):  \n"
  },
  {
    "path": "6sense/findWordInGrid.py",
    "content": "\"\"\"\nRefer below link for the question:\n    https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/\n\nSolution:\n    Algorithm for this is already present, but expected solution should \n    have lowest time complexity (the algorithm should only traverse once unlike the \n    solution above which traverses whole matrix for each word given)\n\nEnhancement: \n    if the word is not present in the grid, print word along with row \n    and col as (-1,-1) like word,-1,-1\n\nHint: \n    Use DP approach\n\nSolution that I have gone with is below:\n\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport sys\nclass word_seek: \n      \n    def __init__(self): \n        self.R = None\n        self.C = None\n        self.dir = [[-1, 0], [1, 0], [1, 1],  \n                    [1, -1], [-1, -1], [-1, 1], \n                    [0, 1], [0, -1]] \n    def search_grid(self, grid, row, col, word): \n        if grid[row][col] != word[0]: \n            return False\n        for x, y in self.dir: \n            rd, cd = row + x, col + y \n            flag = True\n            for k in range(1, len(word)): \n                if (0 <= rd <self.R and \n                    0 <= cd < self.C and \n                    word[k] == grid[rd][cd]):  \n                    rd += x \n                    cd += y \n                else: \n                    flag = False\n                    break       \n            if flag: \n                return True\n        return False  \n    def patternSearch(self, grid, word): \n        self.R = len(grid) \n        self.C = len(grid[0])\n        tracker = []\n        for row in range(self.R): \n            for col in range(self.C): \n                if self.search_grid(grid, row, col, word): \n                    tracker.append((word,row,col))\n                else:\n                    tracker.append((word,-1,-1))\n        if len(set(tracker)) > 1:\n            tracker = sorted(tracker,key=lambda x: x[1],reverse=True)\n            print (tracker[0][0],tracker[0][1],tracker[0][2])\n            return\n        else:\n            assert (tracker[0][1] == -1) and (tracker[0][2] == -1),\"failed\"\n            print (tracker[0][0],tracker[0][1],tracker[0][2])\n            return\n\nif __name__ == '__main__':\n    grid = sys.stdin.readlines()\n    grid = [i.strip() for i in grid]\n    ind = grid.index('')\n    #grid = grid[:(ind)]\n    #finders = grid[(ind+1):]\n    #print (grid)\n    #print (finders)\n    wordSeek = word_seek()\n    for w in grid[(ind+1):]:\n        wordSeek.patternSearch(grid[:(ind)],w)"
  },
  {
    "path": "Accenture/README.md",
    "content": "# Interview Process - Data Engineer - Round 1 (Skills Interview):  \n+ Can a python class have 2 __init__ methods?  \n+ Questions on class methods (staticmethods and classmethods).  \n+ Difference between method and function?  \n+ what are the ways in spark when writing data to storage to reduce or increase number of part files?  \n+ Difference between repartition and coalesce in Spark.  \n+ What is shuffle in spark?  \n+ can data be stored without indexes?  \n+ Object versioning in AWS S3?  \n+ Access contol policies in AWS S3 when creating a bucket?  \n+ Indexing in mongodb?  \n+ Given a small table with field names, write a sql query or spark code to get the required aggregation? refer Window functionality and ranking.  \n+ Differences between client mode and cluster mode (Spark execution) (https://stackoverflow.com/questions/37027732/apache-spark-differences-between-client-and-cluster-deploy-modes).  \n+ Machine learning - classification model - questions on model selection, model evaluation?  \n+ deploy a flask app in azure - what is the approach?  \n+ Questions on azure fundamentals?  \n+ what are the configurations for spark app when spark-submit is done?  \n"
  },
  {
    "path": "Accolite/binaryArraySort.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            N=int(input())\n            A=list(map(int,input().split()))\n            \n            binSort(A,N)\n            \n            for i in A:\n                print(i,end=\" \")\n            print()\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n##Complete this function\ndef binSort(arr, n): \n    #Your code here\n    \n    \n    '''\n    No need to print the array\n    '''\n    c0 = arr.count(0)\n    c1 = arr.count(1)\n    for i in range(c0):\n        arr[i] = 0\n    for i in range(c0,c0+c1):\n        arr[i] = 1"
  },
  {
    "path": "Accolite/merge2SortedLinkedLists.py",
    "content": "{\n#Initial Template for Python 3\n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n,m = map(int, input().strip().split())\n        a = LinkedList() # create a new linked list 'a'.\n        b = LinkedList() # create a new linked list 'b'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_b = list(map(int, input().strip().split()))\n        for x in nodes_a:\n            a.append(x)\n        for x in nodes_b:\n            b.append(x)\n        a.head = merge(a.head,b.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to merge two sorted lists in one\n\tusing constant space.\n\t\n\tFunction Arguments: head_a and head_b (head reference of both the sorted lists)\n\tReturn Type: head of the obtained list after merger.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n\tContributed By: Nagendra Jha\n'''\ndef merge(head_a,head_b):\n    #code here\n    global a\n    elements = []\n    curr_node = head_a\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    curr_node = head_b\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    elements = sorted(elements)\n    a = LinkedList()\n    for i in elements:\n        a.append(i)\n    return a.head"
  },
  {
    "path": "Accolite/rotateLinkedListByKelements.py",
    "content": "{\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    def push(self, new_data):\n        new_node = Node(new_data)\n        new_node.next = self.head\n        self.head = new_node\n    def printList(self):\n        temp = self.head\n        while(temp):\n            print(temp.data, end=\" \")\n            # arr.append(str(temp.data))\n            temp = temp.next\n        print(\"\")\nif __name__ == '__main__':\n    start = LinkedList()\n    t = int(input())\n    while(t > 0):\n        llist = LinkedList()\n        n = int(input())\n        values = list(map(int, input().strip().split()))\n        for i in reversed(values):\n            llist.push(i)\n        k = int(input())\n        new_head = rotateList(llist.head, k)\n        llist.head = new_head\n        llist.printList()\n        t -= 1\n# Contributed by: Harshit Sidhwa\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n# Your task is to complete this function\n'''\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n'''\n# This function should rotate list counter-\n# clockwise by k and return new head (if changed) \ndef rotateList(head, k):\n    # code here\n    global llist\n    llist = LinkedList()\n    C = 0\n    curr_node = head\n    part1 = []\n    part2 = []\n    while curr_node != None:\n        if C <= k-1:\n            part1.append(curr_node.data)\n        elif C > k-1:\n            part2.append(curr_node.data)\n        C += 1\n        curr_node = curr_node.next\n    total = reversed(part2 + part1)\n    for i in total:\n        llist.push(i)\n    return llist.head"
  },
  {
    "path": "Adobe/QuickSort.py",
    "content": "{\n#Initial Template for Python 3\nif __name__ == \"__main__\":\n    t=int(input())\n    for i in range(t):\n        n=int(input())\n        arr=list(map(int,input().split()))\n        quickSort(arr,0,n-1)\n        for i in range(n):\n            print(arr[i],end=\" \")\n        print()\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\ndef quickSort(arr,low,high):\n    if low < high:\n \n        # pi is partitioning index, arr[p] is now\n        # at right place\n        pi = partition(arr,low,high)\n \n        # Separately sort elements before\n        # partition and after partition\n        quickSort(arr, low, pi-1)\n        quickSort(arr, pi+1, high)\n        \ndef partition(arr,low,high):\n    #add code here\n    tmp = 0\n    pivot = arr[high]\n    i = low - 1\n    for j in range(low,high):\n        if arr[j] <= pivot:\n            i += 1\n            tmp = arr[i]\n            arr[i] = arr[j]\n            arr[j] = tmp\n    tmp = arr[i+1]\n    arr[i+1] = arr[high]\n    arr[high] = tmp\n    return i+1"
  },
  {
    "path": "Adobe/WinnerOfElection.py",
    "content": "{\n#Initial Template for Python 3\n    \ndef main():\n    T=int(input())\n    while(T>0):\n        \n        n=int(input())\n        arr=input().strip().split()\n        \n        winner(arr,n)\n        print()\n        \n        T-=1\nif __name__==\"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef winner(arr,n):\n    #Your code here\n    import collections\n    votes = collections.Counter(arr)\n    maxVotes = max(votes.values())\n    if len(set(votes.values())) != len(votes.values()):\n        maxVoteNames = []\n        for k,v in votes.items():\n            if v == maxVotes:\n                maxVoteNames.append(k)\n        print (min(maxVoteNames),maxVotes,end=\"\")\n    else:\n        for k,v in votes.items():\n            if v == maxVotes:\n                print (k,maxVotes,end=\"\")\n                return"
  },
  {
    "path": "Adobe/checkIfStringsAreRotations.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for i in range(t):\n        s1=str(input())\n        s2=str(input())\n        if(areRotations(s1,s2)):\n            print(1)\n        else:\n            print(0)\n    \n        \n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is tocheck if the given two strings\n\tare rotations of each other.\n\tFunction Arguments: s1 and s2 (given strings)\n\tReturn Type:boolean\n'''\ndef areRotations(s1,s2):\n    if (len(s1) == 1 or len(s2) == 1) & (s1 != s2):\n        return False\n    #code here\n    if (len(s1) == len(s2)) & (set(s1)==set(s2)) & (s2 in s1+s2) & (s1 in s1+s2):\n        return True\n    else:\n        return False"
  },
  {
    "path": "Adobe/countOfInversionsArray.py",
    "content": "# GeeksForGeeks Code - Copied#\n{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for tt in range(t):\n        n = int(input())\n        a = list(map(int, input().strip().split()))\n        print(Inversion_Count(a,n))\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to return total number of inversions\n\tpresent in the array.\n\t\n\tFunction Arguments: array a and size n\n\tReturn Type: Integer \n'''\ndef Inversion_Count(arr,n):\n    if a == sorted(a):\n        return 0\n    temp_arr = [0]*n\n    return mergesort(arr,temp_arr,0,n-1)\n    \ndef mergesort(arr,temp_arr,left,right):\n    inv_count = 0\n    if left < right:\n        mid = (left + right)//2\n        inv_count = mergesort(arr,temp_arr,left,mid)\n        inv_count += mergesort(arr,temp_arr,mid+1,right)\n        inv_count += merge(arr,temp_arr,left,mid,right)\n    return inv_count\n    \ndef merge(arr,temp_arr,left, mid, right): \n    # Merge the temp arrays back into arr[l..r] \n    i = left     # Initial index of first subarray \n    j = mid+1     # Initial index of second subarray \n    k = left     # Initial index of merged subarray \n    invcount = 0\n    while i <= mid and j <= right: \n        if arr[i] <= arr[j]:\n            temp_arr[k] = arr[i] \n            i += 1\n        else: \n            temp_arr[k] = arr[j]\n            invcount += (mid - i + 1)\n            j += 1\n        k += 1\n    # Copy the remaining elements of L[], if there \n    # are any \n    while i <= mid: \n        temp_arr[k] = arr[i] \n        i += 1\n        k += 1\n    # Copy the remaining elements of R[], if there \n    # are any \n    while j <= right: \n        temp_arr[k] = arr[j] \n        j += 1\n        k += 1\n        \n    for lr in range(left, right + 1): \n        arr[lr] = temp_arr[lr] \n    return invcount\n"
  },
  {
    "path": "Adobe/parenthesisChecker.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n#Contributed by : Nagendra Jha\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    test_cases = int(input())\n    for cases in range(test_cases) :\n        #n = int(input())\n        #n,k = map(int,imput().strip().split())\n        #a = list(map(int,input().strip().split()))\n        s = str(input())\n        if ispar(s):\n            print(\"balanced\")\n        else:\n            print(\"not balanced\")\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\nFunction Arguments :\n\t\t@param  : s (given string containing parenthesis) \n\t\t@return : boolean True or False\n'''\n\ndef isMatchingPair(c1,c2):\n    if (c1=='(') & (c2==')'):\n        return True\n    elif (c1=='{') & (c2=='}'):\n        return True\n    elif (c1=='[') & (c2==']'):\n        return True\n    else:\n        return False\n        \ndef ispar(s):\n    # code here\n    import queue\n    stack = queue.LifoQueue()\n    \n    for i in range(len(s)):\n        if ((s[i] == '{') | (s[i] == '[') | (s[i] == '(')):\n            stack.put(s[i])\n        if ((s[i] == '}') | (s[i] == ']') | (s[i] == ')')):\n            if stack.empty():\n                return False\n            elif not isMatchingPair(stack.get(),s[i]):\n                return False\n        \n    if stack.empty():\n        return True\n    else:\n        return False"
  },
  {
    "path": "Amazon/DataEngineering/README.md",
    "content": "# Data Engineering Assessment (As of Oct 2024):\n+ Assessment redirected to Hackerank from Amazon Jobs profile configuration.  \n+ Assessment with a maximum duration of 120 mins.  \n+ Multiple Choice Questions on Very basic SQL (Joins, MySQL syntax, Error recognition etc..). Around 20 MCQs.\n+ 3 SQL coding questions, Easy, Medium and Hard [Simple Joins to writing subqueries to ranking + CTEs + Computing Aggregate metrics + subqueries]\n"
  },
  {
    "path": "Amazon/Delete_Node_Without_HeadPointer.py",
    "content": "class Node(object):\n    def __init__(self,dataVal,nextNode=None):\n        self.data = dataVal\n        self.next = nextNode\n        \n    def getData(self):\n        return (self.data)\n    \n    def setData(self,val):\n        self.data = val\n        \n    def getNextNode(self):\n        return (self.next)\n    \n    def setNextNode(self,val):\n        self.next = val\n        \nclass LinkedList(object):\n    def __init__(self,head=None):\n        self.head = head\n        self.size = 0\n        \n    def getSize(self):\n        return (self.size)\n    \n    def addNode(self,data):\n        newNode = Node(data)\n        newNode.setNextNode(self.head)\n        self.head = newNode\n        self.size += 1\n        return True\n    \n    def printNode(self):\n        curr = self.head\n        while curr:\n            print (curr.data)\n            curr = curr.getNextNode()\n        \n    def deleteNode(self,value):\n        \n        prev = None\n        curr = self.head\n        while curr:\n            if curr.data == value:\n                if prev:\n                    prev.setNextNode(curr.getNextNode())\n                else:\n                    self.head = curr.getNextNode()\n                self.size -= 1\n                return True\n                    \n            prev = curr\n            curr = curr.getNextNode()\n            \n        return False\n        \n            \nmyList = LinkedList()\nprint (myList.getSize())\nprint (\"______*Inserting*_______\")\n\nmyList.addNode(5)\nmyList.addNode(10)\nmyList.addNode(15)\nmyList.addNode(20)\nmyList.addNode(25)\n\nprint (\"printing\")\nmyList.printNode()\n\nprint (\"Deleting\")\nmyList.deleteNode(10)\nmyList.deleteNode(20)\nmyList.deleteNode(5)\n\nmyList.addNode(90)\nmyList.addNode(2000)\nprint (myList.getSize())\nmyList.printNode()"
  },
  {
    "path": "Amazon/EquilibriumPointFirstOccurWhere.py",
    "content": "{\n# Initial Template for Python 3\nimport math\ndef main():\n    T = int(input())\n    while(T > 0):\n        N = int(input())\n        A = [int(x) for x in input().strip().split()]\n        print(equilibriumPoint(A, N))\n        T -= 1\nif __name__ == \"__main__\":\n    main()\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n# User function Template for python3\n# Complete this function\ndef equilibriumPoint(A, N):\n    # Your code here\n    if len(A)==1:\n        return 1\n    else:\n        eqlist = []\n        for i in range(1,N-1):\n            if sum(A[:i]) == sum(A[i+1:]):\n                eqlist.append(i+1)\n        if sum(A[1:]) == 0:\n            eqlist.insert(0,1)\n        if sum(A[:N-1]) == 0:\n            eqlist.append(N)\n    if eqlist:\n        return min(eqlist)\n    else:\n        return -1"
  },
  {
    "path": "Amazon/FindzeroSumSubArrays.py",
    "content": "def subArrayExists(arr,n):\n    ##Your code here\n    hashMap = {}\n    out = []\n    sum1 = 0\n    for i in range(n):\n        sum1 += arr[i]\n        if sum1==0:\n            out.append((0,i))\n        al = []\n        if sum1 in hashMap:\n            al = hashMap.get(sum1)\n            for it in range(len(al)):\n                out.append((al[it]+1,i))\n        al.append(i)\n        hashMap[sum1] = al\n    return len(out)\n    \n    \nif __name__ == '__main__':\n    t = int(input())\n    for tcase in range(t):\n        n = int(input())\n        arr = list(map(int,input().strip().split()))\n        print (subArrayExists(arr,n))"
  },
  {
    "path": "Amazon/ImplementSTRSTR.py",
    "content": "{\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        s,p =input().strip().split()\n        print(strstr(s,p))\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n'''\n\tYour task is to return the index of the pattern\n\tpresent in the given string.\n\t\n\tFunction Arguments: s (given text), p(given pattern)\n\tReturn Type: Integer.\n\t\n'''\ndef strstr(s,p):\n    #code here\n    import re\n    loc = re.search(p,s)\n    if loc is not None:\n        return (loc.start())\n    else:\n        return -1"
  },
  {
    "path": "Amazon/JosephusProblem.py",
    "content": "{\nimport math\n//Position this line where user code will be pasted.\n    \ndef main():\n    \n    T=int(input())\n    \n    while(T>0):\n        \n        \n        nk=[int(x) for x in input().strip().split()]\n        n=nk[0]\n        k=nk[1]\n        \n        print(josephus(n,k))\n        \n        T-=1\nif __name__==\"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#Complete this function\ndef josephus(n,k):\n    #Your code here\n    if n == 1:\n        return n\n    return ((josephus(n-1,k)+k-1)%n + 1)"
  },
  {
    "path": "Amazon/MaximumOfMinimumsOfAllWindowSizes.py",
    "content": "#User function Template for python3\n\"\"\"\nGiven an integer array A[] of size N. The task is to find the maximum of the minimum of every window size in the array.\nNote: Window size varies from 1 to n.\n\nInput:\nThe first line contains an integer T denoting the total number of test cases. In each test cases, the first line contains an integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.\n\nOutput:\nIn each seperate line, print the array of numbers of size N for each of the considered window size 1, 2 , ..., N respectively.\n\nUser Task:\nThe task is to complete the function printMaxOfMin() which finds the maximum of minimum of every window size.\n\nConstraints:\n1 <= T <= 50\n1 <= N <= 10^5\n1 <= A[i] <= 10^6\n\nExample:\nInput: \n2\n7\n10 20 30 50 10 70 30\n3\n10 20 30\nOutput: \n70 30 20 10 10 10 10 \n30 20 10\n\nExplaination:\nTestcase 1:\nFirst element in output indicates maximum of minimums of all windows of size 1. Minimums of windows of size 1 are {10}, {20}, {30}, {50}, {10}, {70} and {30}. Maximum of these minimums is 70.\nSecond element in output indicates maximum of minimums of all windows of size 2. Minimums of windows of size 2 are {10}, {20}, {30}, {10}, {10}, and {30}. Maximum of these minimums is 30.\nThird element in output indicates maximum of minimums of all windows of size 3. Minimums of windows of size 3 are {10}, {20}, {10}, {10} and {10}. Maximum of these minimums is 20.\nSimilarly other elements of output are computed.\nTestcase 2: First element in output indicates maximum of minimums of all windows of size 1.Minimums of windows of size 1 are {10} , {20} , {30}. Maximum of these minimums are 30 and similarly other outputs can be computed. \n\"\"\"\n'''\nFunction Arguments :\n      @param  : a(given array), n (size of array)\n      @return : None, print the required Maxofmin array.\n'''\n\ndef printMaxOfMin(a,n):\n    # code here\n    s = []\n    left = [0 for i in range(n+1)]\n    right = [0 for i in range(n+1)]\n    left[:n] = [-1]*n\n    right[:n] = [n]*n\n    for i in range(0,n):\n        while (len(s) != 0 and a[s[-1]] >= a[i]):  \n            s.pop() \n        if (len(s) != 0):\n            left[i] = s[-1]\n        s.append(i)\n    while (len(s) != 0):\n        s.pop()\n    for i in range(n-1,-1,-1):\n        while (len(s) != 0 and a[s[-1]] >= a[i]):\n            s.pop() \n        if (len(s) != 0):\n            right[i] = s[-1]\n        s.append(i)\n    ans = [0]*(n+1)\n    for i in range(0,n):\n        length = right[i] - left[i] - 1\n        ans[length] = max(ans[length],a[i])\n    for i in range(n-1,0,-1):\n        ans[i] = max(ans[i],ans[i+1])\n    for i in range(1,n+1):\n        print (ans[i],end=\" \")\n    print (\"\")\n#{ \n#  Driver Code Starts\n#Initial Template for Python 3\n\nimport atexit\nimport io\nimport sys\n\n#Contributed by : Nagendra Jha\n\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n\n@atexit.register\n\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n\nif __name__ == '__main__':\n    test_cases = int(input())\n    for cases in range(test_cases) :\n        n = int(input())\n        a = list(map(int,input().strip().split()))\n        printMaxOfMin(a,n)\n\n# } Driver Code Ends"
  },
  {
    "path": "Amazon/Possible_Words_Phone_Digits.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n    \n    T=int(input())\n    \n    while(T>0):\n        \n        N=int(input())\n        a=[int(x) for x in input().strip().split()]\n        \n        possibleWords(a,N)\n        \n        print()\n       \n        T-=1\nif __name__==\"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n##Complete this function\ndef possibleWords(a,N):\n    ##Your code here\n    import itertools\n    ph = {'abc':2,'def':3,'ghi':4,'jkl':5,'mno':6,'pqrs':7,'tuv':8,'wxyz':9}\n    my_sts = []\n    for x in a:\n        for k,v in ph.items():\n            if v == x:\n                my_sts.append(k)\n    if len(my_sts)>1:\n        res = list(itertools.product(*my_sts))\n        res = [''.join(u) for u in res]\n        print (' '.join(i for i in res))\n    else:\n        print (' '.join(list(my_sts[0])))"
  },
  {
    "path": "Amazon/countOfInversionsArray.py",
    "content": "# GeeksForGeeks Code - Copied#\n{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for tt in range(t):\n        n = int(input())\n        a = list(map(int, input().strip().split()))\n        print(Inversion_Count(a,n))\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to return total number of inversions\n\tpresent in the array.\n\t\n\tFunction Arguments: array a and size n\n\tReturn Type: Integer \n'''\ndef Inversion_Count(arr,n):\n    if a == sorted(a):\n        return 0\n    temp_arr = [0]*n\n    return mergesort(arr,temp_arr,0,n-1)\n    \ndef mergesort(arr,temp_arr,left,right):\n    inv_count = 0\n    if left < right:\n        mid = (left + right)//2\n        inv_count = mergesort(arr,temp_arr,left,mid)\n        inv_count += mergesort(arr,temp_arr,mid+1,right)\n        inv_count += merge(arr,temp_arr,left,mid,right)\n    return inv_count\n    \ndef merge(arr,temp_arr,left, mid, right): \n    # Merge the temp arrays back into arr[l..r] \n    i = left     # Initial index of first subarray \n    j = mid+1     # Initial index of second subarray \n    k = left     # Initial index of merged subarray \n    invcount = 0\n    while i <= mid and j <= right: \n        if arr[i] <= arr[j]:\n            temp_arr[k] = arr[i] \n            i += 1\n        else: \n            temp_arr[k] = arr[j]\n            invcount += (mid - i + 1)\n            j += 1\n        k += 1\n    # Copy the remaining elements of L[], if there \n    # are any \n    while i <= mid: \n        temp_arr[k] = arr[i] \n        i += 1\n        k += 1\n    # Copy the remaining elements of R[], if there \n    # are any \n    while j <= right: \n        temp_arr[k] = arr[j] \n        j += 1\n        k += 1\n        \n    for lr in range(left, right + 1): \n        arr[lr] = temp_arr[lr] \n    return invcount\n"
  },
  {
    "path": "Amazon/getAggregationsByParsing.py",
    "content": "#!/usr/bin/env python3.9\n# Asked in Thrasio Interview Process\n# Input:\n    \nsales_data = [{'channel':'Amazon', 'id':'AMZ456', 'sales':10, 'returns':0},\n    {'channel':'Amazon', 'id':'AMZ123', 'sales':5, 'returns':2},\n    {'channel':'Shopify', 'id':'1234', 'sales':15, 'returns':0},\n    {'channel':'Target', 'id':'TGT456', 'sales':23, 'returns':5}\n  ]\n \nchannel_thrasio_mapping = {\n    'AMAZON':{'AMZ123':'THRASIO-987', 'AMZ456':'THRASIO-456'},\n  'SHOPIFY':{'1234':'THRASIO-987', '5678':'THRASIO-321'}\n  }\n \n#Expected Output:\n    # [\n#   {'id':'THRASIO-987', 'net_sales':18, 'returns':2},\n#   {'id':'THRASIO-456', 'net_sales':10, 'returns':0},\n# ]\n\nresult = []\nfor k1,v1 in channel_thrasio_mapping.items():\n    for k2,v2 in v1.items():\n        temp_dict = {}\n        temp_dict['id'] = v2\n        all_sales = []\n        all_returns = []\n        for s in sales_data:\n            if s['id'] == k2:\n                all_sales.append(s['sales'])\n                all_returns.append(s['returns'])\n        net_sales = sum(all_sales)-sum(all_returns)\n        returns = sum(all_returns)\n        temp_dict['net_sales'] = net_sales\n        temp_dict['returns'] = returns\n        result.append(temp_dict)\n    \n    \n#print (result)\nunique_thrasio_ids = set([t['id'] for t in result])\n#print (unique_thrasio_ids)\n\noutput = []\nfor utd in unique_thrasio_ids:\n    final_result = {}\n    final_result['id'] = utd\n    final_result['net_sales'] = 0\n    final_result['returns'] = 0\n    for res in result:\n        if res['id'] == utd:\n            final_result['net_sales'] += res['net_sales']\n            final_result['returns'] += res['returns']\n    output.append(final_result)\n\nprint (output)\n"
  },
  {
    "path": "Amazon/keypadTyping.py",
    "content": "def keypadTyping(s):\n    for c in s:\n        print (mydict[c],end=\"\")\n    \nif __name__ == '__main__':\n    t = int(input())\n    mydict = {'a':2,'b':2,'c':2,\n              'd':3,'e':3,'f':3,\n              'g':4,'h':4,'i':4,\n              'j':5,'k':5,'l':5,\n              'm':6,'n':6,'o':6,\n              'p':7,'q':7,'r':7,'s':7,\n              't':8,'u':8,'v':8,\n              'w':9,'x':9,'y':9,'z':9}\n    for tcase in range(t):\n        s = input()\n        keypadTyping(s)\n        print ()"
  },
  {
    "path": "Amazon/merge2SortedLinkedLists.py",
    "content": "{\n#Initial Template for Python 3\n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n,m = map(int, input().strip().split())\n        a = LinkedList() # create a new linked list 'a'.\n        b = LinkedList() # create a new linked list 'b'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_b = list(map(int, input().strip().split()))\n        for x in nodes_a:\n            a.append(x)\n        for x in nodes_b:\n            b.append(x)\n        a.head = merge(a.head,b.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to merge two sorted lists in one\n\tusing constant space.\n\t\n\tFunction Arguments: head_a and head_b (head reference of both the sorted lists)\n\tReturn Type: head of the obtained list after merger.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n\tContributed By: Nagendra Jha\n'''\ndef merge(head_a,head_b):\n    #code here\n    global a\n    elements = []\n    curr_node = head_a\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    curr_node = head_b\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    elements = sorted(elements)\n    a = LinkedList()\n    for i in elements:\n        a.append(i)\n    return a.head"
  },
  {
    "path": "Amazon/missingSmallestPositiveNumber.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            n=int(input())\n            \n            arr=[int(x) for x in input().strip().split()]\n            \n            print(missingNumber(arr,n))\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n##Complete this function\ndef missingNumber(arr,n):\n    #Your code here\n    poss = [x for x in arr if x > 0]\n    if poss:\n        if poss == list(range(1,n+1)):\n            return max(poss)+1\n        else:\n            min_poss = min(poss)\n            max_poss = max(poss)\n            total_range = list(range(1,max_poss+1))\n            missingNumbers = set(total_range) - set(poss)\n            return min(missingNumbers)\n    else:\n        return 0"
  },
  {
    "path": "Amazon/moveAllZerosToEndOfArray.py",
    "content": "def moveZerosToEnd(arr):\n    arr_0 = [x for x in arr if x!=0]\n    zeros = [0] * (len(arr)-len(arr_0))\n    ans = arr_0 + zeros\n    return \" \".join(str(u) for u in ans)\n\nif __name__ == '__main__':\n    T = int(input())\n    for t in range(T):\n        N = int(input())\n        arr = list(map(int,input().strip().split()))\n        print (moveZerosToEnd(arr))"
  },
  {
    "path": "Amazon/parenthesisChecker.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n#Contributed by : Nagendra Jha\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    test_cases = int(input())\n    for cases in range(test_cases) :\n        #n = int(input())\n        #n,k = map(int,imput().strip().split())\n        #a = list(map(int,input().strip().split()))\n        s = str(input())\n        if ispar(s):\n            print(\"balanced\")\n        else:\n            print(\"not balanced\")\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\nFunction Arguments :\n\t\t@param  : s (given string containing parenthesis) \n\t\t@return : boolean True or False\n'''\n\ndef isMatchingPair(c1,c2):\n    if (c1=='(') & (c2==')'):\n        return True\n    elif (c1=='{') & (c2=='}'):\n        return True\n    elif (c1=='[') & (c2==']'):\n        return True\n    else:\n        return False\n        \ndef ispar(s):\n    # code here\n    import queue\n    stack = queue.LifoQueue()\n    \n    for i in range(len(s)):\n        if ((s[i] == '{') | (s[i] == '[') | (s[i] == '(')):\n            stack.put(s[i])\n        if ((s[i] == '}') | (s[i] == ']') | (s[i] == ')')):\n            if stack.empty():\n                return False\n            elif not isMatchingPair(stack.get(),s[i]):\n                return False\n        \n    if stack.empty():\n        return True\n    else:\n        return False"
  },
  {
    "path": "Amazon/relativeSorting.py",
    "content": "def relativeSorting(A1,A2):\n    common_elements = set(A1).intersection(set(A2))\n    extra = set(A1).difference(set(A2))\n    out = []\n    for i in A2:\n        s = [i] * A1.count(i)\n        out.extend(s)\n    extra_out = []\n    for j in extra:\n        u = [j] * A1.count(j)\n        extra_out.extend(u)\n    out = out + sorted(extra_out)\n    return \" \".join(str(i) for i in out)\n    \nif __name__ == '__main__':\n    t = int(input())\n    for tcase in range(t):\n        N,M = list(map(int,input().strip().split()))\n        A1 = list(map(int,input().strip().split()))\n        A2 = list(map(int,input().strip().split()))\n        print (relativeSorting(A1,A2))"
  },
  {
    "path": "Amazon/rotateLinkedListByKelements.py",
    "content": "{\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    def push(self, new_data):\n        new_node = Node(new_data)\n        new_node.next = self.head\n        self.head = new_node\n    def printList(self):\n        temp = self.head\n        while(temp):\n            print(temp.data, end=\" \")\n            # arr.append(str(temp.data))\n            temp = temp.next\n        print(\"\")\nif __name__ == '__main__':\n    start = LinkedList()\n    t = int(input())\n    while(t > 0):\n        llist = LinkedList()\n        n = int(input())\n        values = list(map(int, input().strip().split()))\n        for i in reversed(values):\n            llist.push(i)\n        k = int(input())\n        new_head = rotateList(llist.head, k)\n        llist.head = new_head\n        llist.printList()\n        t -= 1\n# Contributed by: Harshit Sidhwa\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n# Your task is to complete this function\n'''\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n'''\n# This function should rotate list counter-\n# clockwise by k and return new head (if changed) \ndef rotateList(head, k):\n    # code here\n    global llist\n    llist = LinkedList()\n    C = 0\n    curr_node = head\n    part1 = []\n    part2 = []\n    while curr_node != None:\n        if C <= k-1:\n            part1.append(curr_node.data)\n        elif C > k-1:\n            part2.append(curr_node.data)\n        C += 1\n        curr_node = curr_node.next\n    total = reversed(part2 + part1)\n    for i in total:\n        llist.push(i)\n    return llist.head"
  },
  {
    "path": "AmericanExpress/README.md",
    "content": "# Interview Process for Engineer - II (2021) (Personal):  \n### First Round - Coding Round: Online Coding Round with time management.  \n### Second Round - Design:  \n+ Design an Application that serves machine learning model results in real-time (Design a feedback ingestion system and notifications pusher) - Brush upon \nsystem design concepts, NoSQL Databases, caching, load balancer frameworks, distributed computing fundamentals, APIs, software design patterns.  \n\n### Third Round - Technical:  \n+ Implement KNN (K-Nearest neighbors) algorithm at scale - Start from scratch - Try to think of solution that doesn't rely on existing cluster computing frameworks \nlike spark, Dask etc - performance and efficient design matters!  - very good question, completely depends on the distributed and parallel processing paradigms and \noperating systems knowledge.  \n"
  },
  {
    "path": "Athena-Health/README.md",
    "content": "# Interview Process for SMTS (Senior Member of Technical Staff) - 2021:  \n### First Round - Coding (Data Structures and Algorithms):  \n+ Given an array with 0s, 1s and 2s - sort the array without actually doing sorting (Incase of python - Avoid using built-in functions for any operations).  \n+ Given an unsorted array, Find the median of the given array (Do not use any libraries and functions, Raw code has to be written).  \n  \n  \n### Second Round - Design:  \n+ In-Depth questions on BSTs and graphs.  \n+ Real time Application use-case involving updation of news feed/facebook feed/twitter feed based on ranking of the incoming data stream of posts, comments, reactions such that posts are sorted by highest rank followed by post with lesser rank and so on - Do this in real time - Design an efficient feed management system.  \n\n### Third Round - Managerial:  \n+ Questions on your technical experience and projects you have done.  \n+ Challenges in the projects, how are scaling issues resolved, Team work, Milestones achieved etc.  \n+ Questions on Deployment process followed and tools used for deploying codebase - devops architecture, CI/CD, Docker, Kubernetes, Service mesh and containerization etc\n\n### Fourth Round - HR round:  \n+ Questions are similar to questions from any other HR round.  \n+ what are you looking for? what are your career aspirations?  \n+ what are your interests and why are you interested in athenahealth?\n+ Any other doubts and clarifications on the role, Planning connects with Hiring manager etc.\n"
  },
  {
    "path": "Betterworks/README.md",
    "content": "# Hiring process for Betterworks Software Engineer Role (Personal Experience):  \n  \n## First round:  \n+ Discussion from Director of Engineering/Lead Engineer on your work experience, Job description, you expertise on skills required for the role, understand your skillset, projects that you have worked in and have been working on at the moment - critical challenges faced and how you have overcome them etc.  \n  \n## Second round:  \n+ Technical screening on basic coding questions.  \n+ Basic questions on pandas data munging steps, write a simple algorithm (Given a pair of string and numbers ex: one 1, two 2, three 3, four 4, five 5 - print sequence like this - (n,1),(w,2),(r,3),(ou,4),(iv,5).  \n+ sorting techniques, python built-in data structures and questions on the same.  \n+ questions on python decorators.  \n  \n## Third round:  \n+ Hands-on Assignment where you have to build a working prototype of an API (Assignment will be shared in the form of PDF).  \n  \n## Fourth round:  \n+ Questions on pandas data analysis techniques  groupby, aggregations, distributions, visualizing the bar charts, boxplots.  \n+ SQL - primary keys, foreign keys, composite keys, Indexes, star and snowflake schemas.  \n+ Write an algorithm that does the following, Given a array of integers and element x - find all the elements of array that are closer to given number x (Numbers having minimum difference with x)(questions on time complexity, scope for optimization,efficiency).  \n+ Questions on Github, process of deployment and development you follow in your regular projects at work with github. when would you use git squash, git merge, git rebase etc.  \n+ Questions on REST API, design techniques etc.  \n"
  },
  {
    "path": "Betterworks/print.py",
    "content": "\"\"\"\nGiven a dictionary of elements:\n    mydict = {'one':1,\n              'two':2,\n              'three':3,\n              'four':4,\n              'five':5}\n    print the sequence of elements in the following fashion:\n        {'n':1,'w':2,'r':3,'ou':4,'iv':5}\n        \n\"\"\"\n\nmydict = {'one':1,\n              'two':2,\n              'three':3,\n              'four':4,\n              'five':5}\n\ndef doop(mydict):\n    if len(mydict) == 0:\n        return \"no data\"\n    res = {}\n    for k,v in mydict.items():\n        leng = len(k)\n        if leng%2 != 0:\n            res.update({k[(leng-1)//2]:v})\n        else:\n            key = ''.join([k[(leng-1)//2],k[(leng+1)//2]])\n            res.update({key:v})\n    return res\n\nprint (doop(mydict))"
  },
  {
    "path": "Bloomberg/moveAllZerosToEndOfArray.py",
    "content": "def moveZerosToEnd(arr):\n    arr_0 = [x for x in arr if x!=0]\n    zeros = [0] * (len(arr)-len(arr_0))\n    ans = arr_0 + zeros\n    return \" \".join(str(u) for u in ans)\n\nif __name__ == '__main__':\n    T = int(input())\n    for t in range(T):\n        N = int(input())\n        arr = list(map(int,input().strip().split()))\n        print (moveZerosToEnd(arr))"
  },
  {
    "path": "BrightMoney/Knapsack.py",
    "content": "\"\"\"\n0-1 Knapsack problem\n\n\"\"\""
  },
  {
    "path": "BrightMoney/LongestBalancedSubstring.py",
    "content": "\"\"\"\nLongest balanced substring given a string containing only parenthesis (open and\nclosed curly braces)\n\nRefer https://www.geeksforgeeks.org/length-of-the-longest-valid-substring/\nalong with the length, also print the start and end indices of this longest substring\n\nRefer below custom addition to the existing code\n\n\"\"\"\n\n\ndef findMaxLen(string): \n    n = len(string) \n  \n    # Create a stack and push -1 as initial index to it. \n    stk = [] \n    stk.append(-1) \n  \n    # Initialize result \n    result = 0\n    tracker = []\n  \n    # Traverse all characters of given string \n    for i in range(n): \n      \n        # If opening bracket, push index of it \n        if string[i] == '{': \n            stk.append(i) \n  \n        else:    # If closing bracket, i.e., str[i] = '}' \n      \n            # Pop the previous opening bracket's index \n            stk.pop() \n      \n            # Check if this length formed with base of \n            # current valid substring is more than max  \n            # so far \n            if len(stk) != 0: \n                if result < i - stk[len(stk)-1]:\n                    result = i - stk[len(stk)-1]\n                    tracker.append((result,i))\n  \n            # If stack is empty. push current index as  \n            # base for next valid substring (if any) \n            else: \n                stk.append(i) \n  \n    return result,tracker\n\n#string = \"{{{}\"\n#string = \"}{}{}}\"\nstring = \"{}{{}}}}}\"\nresult,tracker = findMaxLen(string)\nfor t in tracker:\n    if t[0] == result:\n        end_index = t[1]\n        \n# length of longest substring (balanced)\nprint (result)\n\n# print (start and end locations of that substring)\nprint (\" \".join([str(end_index - result + 2),str(end_index + 1)]))"
  },
  {
    "path": "BrightMoney/README.md",
    "content": "# Coding questions on DoSelect Platform (Personal Experience) (Data Science roles - ML Engineering) (4 Coding questions are added here)  \n+  This process is different from Data analyst process.  \n  \n# Interview Process for Data Analyst position:  \n## First round - DoSelect Assessment for Data Analyst positions/Word Document on email:  \n+ There are different kinds of assessments being used by BrightMoney for Data analyst positions:  \n  - It can send you a word document (Refer word document above) consisting of questions & asking you to write sql queries for different scenarios in the document and also to replicate the same logic using pandas in python (use sqlite).  \n  - It can also send you DoSelect link where there are two questions, one question to be solved using pandas for simple data manipulation and other is you have to write a sql query (Given different tables by showing relationships between all tables like an ER diagram with indications of primary and foreign keys)  \n  \n## Second round - Business Case study from the founder of Brightmoney.co:  \n+ Given a case study around credit cards and checking accounts with financial lingo, build your hypothesis and present a solution as to why you think your approach is accurate compared to other possible approaches? What are the different problems with your approach? What can be challenges with the data you are taking? etc (Deleted the case study ppt to avoid DMCA notices).  \n"
  },
  {
    "path": "BrightMoney/countDistinctValidPANNumbers.py",
    "content": "\"\"\"\nGiven a paragraph of P words, find all valid PAN card numbers in that paragraph\n\"\"\""
  },
  {
    "path": "BrightMoney/printSpirally.py",
    "content": "\"\"\"\nGiven an integer n, generate a square matrix from entries from 1 to n**2 in \nspiral pattern\n\n\"\"\"\n\ndef generateMatrix(n):\n    if n <= 0:\n        return []\n    result = [[None for i in range(n)] for j in range(n)]\n    xBeg,xEnd = 0,n-1\n    yBeg,yEnd = 0,n-1\n    current = 1\n    while (True):\n        for i in range(yBeg,yEnd+1):\n            result[xBeg][i] = current\n            current += 1\n        xBeg += 1\n        if (xBeg > xEnd):\n            break\n        for i in range(xBeg,xEnd+1):\n            result[i][yEnd] = current\n            current += 1\n        yEnd -= 1\n        if (yEnd < yBeg):\n            break\n        for i in range(yEnd,yBeg-1,-1):\n            result[xEnd][i] = current\n            current += 1\n        xEnd -= 1\n        if (xEnd < xBeg):\n            break\n        for i in range(xEnd,xBeg-1,-1):\n            result[i][yBeg] = current\n            current += 1\n        yBeg += 1\n        if (yBeg > yEnd):\n            break\n    return result\n        \nrows = generateMatrix(9)\nfor row in rows:\n    print (\" \".join(str(i) for i in row))"
  },
  {
    "path": "Busigence/README.md",
    "content": "# Interview Process - Personal (Data Engineer - Python/Pyspark/Scala-spark) - 2021:  \n### First round:  \n+ Take Home assignment on Spark coding.  \n+ The solutions added above are correct (Got selected to next round) 👍 🙂.  \n"
  },
  {
    "path": "Busigence/Vikas_Chitturi.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"DATA ENGINEER - PYTHON PYSPARK\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"This test consits of fifteen problems. You are required to write your code in cell below each problem and output the result in cell next to it \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Total Time Allowed: 3 hours\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Style1: 10 markes each shall be awarded for correct solution coded in object oriented paradign in Python3 <br>\\n\",\n    \"Style2: 15 marks each shall be awarded for correct solution coded in functional programming paradigm (lamda, map, reduce, filter etc) in Python3 <br>\\n\",\n    \"Style3: 20 marks each shall be awarded for correct solution coded in functional programming paradigm (dataframes, map, reduce, filter etc) in PySpark3\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Rename and Save the notebook with your FirstName_LastName (eg. Sahil_Gupta.ipynb)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"#Vikas Veerabhadra Chitturi\\n\",\n    \"#XXXXXXXXXXXXXXXX\\n\",\n    \"#+91-XXXXXXXXXX\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"********************************************* Test starts here **************************************************\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"INSTRUCTIONS:\\n\",\n    \"    1. You are required to download and import five CSV files, one json file and one xml file\\n\",\n    \"    2. You would need to understand business involved behind CRM database tables. This is important\\n\",\n    \"    3. Code must be in Python3/PySpark3\\n\",\n    \"    4. Either your code should output something or leave the comment \\\"#solution code here\\\" as it is. We shall use 'Run All' in notebook and it shouldn't result error\\n\",\n    \"    5. Test the entire notebook before uploading to Google Form provided\\n\",\n    \"    6. You can use any Python3 library (two are imported already) or PySpark3 library. There is no restriction\\n\",\n    \"    7. Output fieldname to be displayed are marked as single quaotes '' in problem statement. You should use same field alias names whereever required\\n\",\n    \"    8. Notation for dataframe and/or array must be local to a problem's solution. Eg. Dataframe \\\"test\\\" for problem 8 should be df_prb8_test\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"import pandas as pd\\n\",\n    \"from pyspark.sql import SparkSession\\n\",\n    \"from pyspark.sql.functions import *\\n\",\n    \"from pyspark.sql.types import *\\n\",\n    \"from collections import defaultdict\\n\",\n    \"import json\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"<pyspark.sql.session.SparkSession object at 0x7fa7a6083040>\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#Please make sure this notebook is run on spark installed cluster/environment - Data processing is done in pyspark\\n\",\n    \"spark = SparkSession.builder\\\\\\n\",\n    \"          .master(\\\"local[4]\\\")\\\\\\n\",\n    \"          .appName(\\\"Assignment\\\")\\\\\\n\",\n    \"          .getOrCreate()\\n\",\n    \"print (spark)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Sales Teams...\\n\",\n      \"[Row(sales_agent='Donn Cantrell', manager='Rocco Neubert', regional_office='Central'), Row(sales_agent='James Ascencio', manager='Summer Sewald', regional_office='West'), Row(sales_agent='Vicki Laflamme', manager='Celia Rouche', regional_office='West'), Row(sales_agent='Niesha Huffines', manager='Melvin Marxen', regional_office='East'), Row(sales_agent='Kami Bicknell', manager='Summer Sewald', regional_office='West')]\\n\",\n      \"Accounts....\\n\",\n      \"[Row(account='Sunnamplex', revenue='4592.96', employees='13938.0'), Row(account='Silis', revenue='5339.57', employees='18053.0'), Row(account='Groovestreet', revenue='2728.86', employees='6486.0'), Row(account='Donware', revenue='2009.52', employees='3409.0'), Row(account='Wonka Industries', revenue='4962.27', employees='4687.0')]\\n\",\n      \"Clicks....\\n\",\n      \"[Row(created_on='2016-11-14', source='Referral', industry='IT'), Row(created_on='2016-11-14', source='Social', industry='IT'), Row(created_on='2016-11-14', source='Paid', industry='SaaS'), Row(created_on='2016-11-14', source='Direct', industry='SaaS'), Row(created_on='2016-11-15', source='Organic', industry='Health Care')]\\n\",\n      \"Products....\\n\",\n      \"[Row(product='GTXAdvanced', sales_price='649.0'), Row(product='GTXBasic', sales_price='641.0'), Row(product='MGRPFU', sales_price='3959.0'), Row(product='MGRPFS', sales_price='64.0'), Row(product='GTXPlusBasic', sales_price='1279.0')]\\n\",\n      \"Sales Pipeline....\\n\",\n      \"[Row(account='Sunnamplex', opportunity_id='67HY0MW7', sales_agent='Donn Cantrell', deal_stage='Won', product='GTXBasic', close_date='2017-05-06', close_value='500.0', created_on='2017-04-24'), Row(account=None, opportunity_id='MA82HVCI', sales_agent='James Ascencio', deal_stage='In_Progress', product='GTXPro', close_date=None, close_value=None, created_on='2017-06-15'), Row(account=None, opportunity_id='BRL1KVVH', sales_agent='Vicki Laflamme', deal_stage='Lost', product='GTXBasic', close_date='2017-08-03', close_value='0.0', created_on='2017-05-19'), Row(account='Silis', opportunity_id='R22O68FF', sales_agent='Niesha Huffines', deal_stage='Won', product='GTXBasic', close_date='2017-06-27', close_value='524.0', created_on='2017-03-21'), Row(account='Silis', opportunity_id='J78AK31N', sales_agent='Kami Bicknell', deal_stage='Won', product='MGRPFU', close_date='2017-08-04', close_value='4794.0', created_on='2017-05-15')]\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#import CSVs here\\n\",\n    \"df_sales_teams = spark.read.format('csv')\\\\\\n\",\n    \"                      .option(\\\"header\\\",\\\"true\\\")\\\\\\n\",\n    \"                      .load(\\\"data/sales_teams.csv\\\")\\n\",\n    \"df_accounts = spark.read.format('csv')\\\\\\n\",\n    \"                      .option(\\\"header\\\",\\\"true\\\")\\\\\\n\",\n    \"                      .load(\\\"data/accounts.csv\\\")\\n\",\n    \"df_clicks = spark.read.format('csv')\\\\\\n\",\n    \"                      .option(\\\"header\\\",\\\"true\\\")\\\\\\n\",\n    \"                      .load(\\\"data/clicks.csv\\\")\\n\",\n    \"df_products = spark.read.format('csv')\\\\\\n\",\n    \"                      .option(\\\"header\\\",\\\"true\\\")\\\\\\n\",\n    \"                      .load(\\\"data/products.csv\\\")\\n\",\n    \"df_sales_pipeline = spark.read.format('csv')\\\\\\n\",\n    \"                      .option(\\\"header\\\",\\\"true\\\")\\\\\\n\",\n    \"                      .load(\\\"data/sales_pipeline.csv\\\")\\n\",\n    \"\\n\",\n    \"print (\\\"Sales Teams...\\\")\\n\",\n    \"print (df_sales_teams.take(5))\\n\",\n    \"\\n\",\n    \"print (\\\"Accounts....\\\")\\n\",\n    \"print (df_accounts.take(5))\\n\",\n    \"\\n\",\n    \"print (\\\"Clicks....\\\")\\n\",\n    \"print (df_clicks.take(5))\\n\",\n    \"\\n\",\n    \"print (\\\"Products....\\\")\\n\",\n    \"print (df_products.take(5))\\n\",\n    \"\\n\",\n    \"print (\\\"Sales Pipeline....\\\")\\n\",\n    \"print (df_sales_pipeline.take(5))\\n\",\n    \"\\n\",\n    \"#import JSONs here\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Refer & Use five CSVs to answer problem 1-10 below\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 1: Display 'Manager' and 'Grand Total Sales', for sales done by the sales agents reporting these managers\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+-------------+-------------+-----------+-----------+\\n\",\n      \"|  sales_agent|      manager| deal_stage|close_value|\\n\",\n      \"+-------------+-------------+-----------+-----------+\\n\",\n      \"|Donn Cantrell|Rocco Neubert|        Won|      444.0|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|In_Progress|       null|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|       Lost|        0.0|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|        Won|     7695.0|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|        Won|     5531.0|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|In_Progress|       null|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|        Won|     7381.0|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|        Won|      565.0|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|In_Progress|       null|\\n\",\n      \"|Donn Cantrell|Rocco Neubert|        Won|     7905.0|\\n\",\n      \"+-------------+-------------+-----------+-----------+\\n\",\n      \"only showing top 10 rows\\n\",\n      \"\\n\",\n      \"14277\\n\",\n      \"+----------------+-----------------+\\n\",\n      \"|         manager|grand_total_sales|\\n\",\n      \"+----------------+-----------------+\\n\",\n      \"|    Celia Rouche|        2518466.0|\\n\",\n      \"|   Rocco Neubert|        3346813.0|\\n\",\n      \"|   Melvin Marxen|        4265901.0|\\n\",\n      \"|   Summer Sewald|        2915362.0|\\n\",\n      \"|      Cara Losch|        1861751.0|\\n\",\n      \"|Dustin Brinkmann|        3028635.0|\\n\",\n      \"+----------------+-----------------+\\n\",\n      \"\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"#joining sales_teams and sales_pipeline tables\\n\",\n    \"df_st_sp_prob1 = df_sales_teams.select(\\\"sales_agent\\\",\\\"manager\\\").alias(\\\"a\\\")\\\\\\n\",\n    \"                         .join(df_sales_pipeline.select(\\\"sales_agent\\\",\\\"deal_stage\\\",\\\"close_value\\\").alias(\\\"b\\\"),\\n\",\n    \"                               on=col(\\\"a.sales_agent\\\")==col(\\\"b.sales_agent\\\"),how='left')\\\\\\n\",\n    \"                         .select([col(\\\"a.sales_agent\\\"),col(\\\"a.manager\\\"),col(\\\"b.deal_stage\\\"),col(\\\"b.close_value\\\")])\\n\",\n    \"df_st_sp_prob1.show(10) \\n\",\n    \"print (df_st_sp_prob1.count())\\n\",\n    \"#putting a filter on deal_stage=='Won' because it is considered as successful sale completed and close_value is the\\n\",\n    \"#final value for which product is sold after negotiation\\n\",\n    \"df_st_sp_prob1 = df_st_sp_prob1.filter(col(\\\"deal_stage\\\")==\\\"Won\\\")\\n\",\n    \"df_st_sp_prob1 = df_st_sp_prob1.withColumn(\\\"close_value\\\",df_st_sp_prob1[\\\"close_value\\\"].cast(DoubleType()))\\n\",\n    \"result_prob1 = df_st_sp_prob1.groupBy(\\\"manager\\\").agg(sum(\\\"close_value\\\").alias(\\\"grand_total_sales\\\"))\\n\",\n    \"result_prob1.show()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 2: Display 'Sales Agents' and 'Sales' for those sales where product sold at profit\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------+-----------------+----------+------------+-----------+------------+\\n\",\n      \"|opportunity_id|      sales_agent|deal_stage|     product|final_price|actual_price|\\n\",\n      \"+--------------+-----------------+----------+------------+-----------+------------+\\n\",\n      \"|      67HY0MW7|    Donn Cantrell|       Won|    GTXBasic|      500.0|       641.0|\\n\",\n      \"|      R22O68FF|  Niesha Huffines|       Won|    GTXBasic|      524.0|       641.0|\\n\",\n      \"|      J78AK31N|    Kami Bicknell|       Won|      MGRPFU|     4794.0|      3959.0|\\n\",\n      \"|      8I9PRPGN|Versie Hillebrand|       Won|      MGRPFS|       67.0|        64.0|\\n\",\n      \"|      4VHUTHOJ|    Kami Bicknell|       Won|GTXPlusBasic|     1480.0|      1279.0|\\n\",\n      \"|      TMJ0OJ0B|  Kary Hendrixson|       Won|    GTXBasic|      635.0|       641.0|\\n\",\n      \"|      MD4PBMNN|    Anna Snelling|       Won|      MGRPFU|     3842.0|      3959.0|\\n\",\n      \"|      1XPVT5AY|  Kary Hendrixson|       Won|  GTXPlusPro|     5055.0|      6395.0|\\n\",\n      \"|      IH2QISS9|  Kary Hendrixson|       Won|      GTXPro|     4889.0|      5624.0|\\n\",\n      \"|      7JJ73XCX|   James Ascencio|       Won|GTXPlusBasic|     1226.0|      1279.0|\\n\",\n      \"|      T8QRTV6F|   James Ascencio|       Won|  GTXPlusPro|     9150.0|      6395.0|\\n\",\n      \"|      C7NFUAR6|Marty Freudenburg|       Won|GTXPlusBasic|     1380.0|      1279.0|\\n\",\n      \"|      NXRZZBVS|  Lajuana Vencill|       Won|      MGRPFU|     3620.0|      3959.0|\\n\",\n      \"|      H7ZQUWDJ|     Reed Clapper|       Won|    GTXBasic|      660.0|       641.0|\\n\",\n      \"|      YV47EGIC|    Anna Snelling|       Won|      MGRPFS|       44.0|        64.0|\\n\",\n      \"|      SC4LUMPZ|     Elease Gluck|       Won|      MGRPFS|       64.0|        64.0|\\n\",\n      \"|      ZES3NR0F|Versie Hillebrand|       Won|      MGRPFS|       54.0|        64.0|\\n\",\n      \"|      KJ1JOOQ0|  Niesha Huffines|       Won|      MGRPFS|       61.0|        64.0|\\n\",\n      \"|      ZHV68QKO|     Reed Clapper|       Won|      GTXPro|     4551.0|      5624.0|\\n\",\n      \"|      4RE1ST7V|    Kami Bicknell|       Won|  GTXPlusPro|     5213.0|      6395.0|\\n\",\n      \"+--------------+-----------------+----------+------------+-----------+------------+\\n\",\n      \"only showing top 20 rows\\n\",\n      \"\\n\",\n      \"6438\\n\",\n      \"+--------------+------------------+------------+-----------+------------+\\n\",\n      \"|opportunity_id|       sales_agent|     product|final_price|actual_price|\\n\",\n      \"+--------------+------------------+------------+-----------+------------+\\n\",\n      \"|      J78AK31N|     Kami Bicknell|      MGRPFU|     4794.0|      3959.0|\\n\",\n      \"|      8I9PRPGN| Versie Hillebrand|      MGRPFS|       67.0|        64.0|\\n\",\n      \"|      4VHUTHOJ|     Kami Bicknell|GTXPlusBasic|     1480.0|      1279.0|\\n\",\n      \"|      T8QRTV6F|    James Ascencio|  GTXPlusPro|     9150.0|      6395.0|\\n\",\n      \"|      C7NFUAR6| Marty Freudenburg|GTXPlusBasic|     1380.0|      1279.0|\\n\",\n      \"|      H7ZQUWDJ|      Reed Clapper|    GTXBasic|      660.0|       641.0|\\n\",\n      \"|      8S4H8GNZ|      Reed Clapper|      MGRPFU|     4750.0|      3959.0|\\n\",\n      \"|      P007M3B8| Marty Freudenburg|      MGRPFS|       75.0|        64.0|\\n\",\n      \"|      KI49INQW|  Gladys Colclough|GTXPlusBasic|     1524.0|      1279.0|\\n\",\n      \"|      2NAKBIH8|      Reed Clapper|      GTXPro|     7007.0|      5624.0|\\n\",\n      \"|      TGYPRG6Y|    Wilburn Farren|GTXPlusBasic|     1566.0|      1279.0|\\n\",\n      \"|      H8ONBK8M|   Kary Hendrixson|GTXPlusBasic|     1631.0|      1279.0|\\n\",\n      \"|      WB5W4F6P|      Reed Clapper|      GTXPro|     6894.0|      5624.0|\\n\",\n      \"|      VB2E4FRU|      Elease Gluck|      MGRPFU|     4712.0|      3959.0|\\n\",\n      \"|      VUNCUB75|Jonathan Berthelot|GTXPlusBasic|     1307.0|      1279.0|\\n\",\n      \"|      9UAMZCLW|      Elease Gluck|      MGRPFU|     4389.0|      3959.0|\\n\",\n      \"|      FH7HBET2|       Moses Frase|GTXPlusBasic|     1509.0|      1279.0|\\n\",\n      \"|      WHRDPR4H|   Darcel Schlecht|    GTXBasic|      875.0|       641.0|\\n\",\n      \"|      9L5HPLM6|   Niesha Huffines|    GTXBasic|      688.0|       641.0|\\n\",\n      \"|      AZF4JUJH|     Kami Bicknell|      MGRPFS|       66.0|        64.0|\\n\",\n      \"+--------------+------------------+------------+-----------+------------+\\n\",\n      \"only showing top 20 rows\\n\",\n      \"\\n\",\n      \"3386\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"#joining sales_pipeline and products tables to get the mapping of actual and final prices\\n\",\n    \"df_sp_prod_prob2 = df_sales_pipeline.filter(col(\\\"deal_stage\\\")==\\\"Won\\\")\\\\\\n\",\n    \"                         .select(\\\"opportunity_id\\\",\\\"sales_agent\\\",\\\"deal_stage\\\",\\\"product\\\",\\\"close_value\\\").alias(\\\"a\\\")\\\\\\n\",\n    \"                         .join(df_products.select(\\\"product\\\",\\\"sales_price\\\").alias(\\\"b\\\"),\\n\",\n    \"                               on=col(\\\"a.product\\\")==col(\\\"b.product\\\"),how='left')\\\\\\n\",\n    \"                         .select([col(\\\"a.opportunity_id\\\"),col(\\\"a.sales_agent\\\"),col(\\\"a.deal_stage\\\"),col(\\\"a.product\\\"),\\n\",\n    \"                                  col(\\\"a.close_value\\\").alias(\\\"final_price\\\"),\\n\",\n    \"                                  col(\\\"b.sales_price\\\").alias(\\\"actual_price\\\")])\\n\",\n    \"df_sp_prod_prob2.show(20)\\n\",\n    \"print (df_sp_prod_prob2.count())\\n\",\n    \"\\n\",\n    \"#profit means final price (close_value) is greater than actual price (sales_price)\\n\",\n    \"result_prob2 = df_sp_prod_prob2.where(col(\\\"final_price\\\") > col(\\\"actual_price\\\"))\\n\",\n    \"result_prob2 = result_prob2.select(\\\"opportunity_id\\\",\\\"sales_agent\\\",\\\"product\\\",\\\"final_price\\\",\\\"actual_price\\\")\\n\",\n    \"result_prob2.show()\\n\",\n    \"print (result_prob2.count())\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 3: Display the 'Opportunity ID' and 'Days Taken to Close', for opportunities those got closed within a month\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------+----------------+\\n\",\n      \"|opportunity_id|DaysTakenToClose|\\n\",\n      \"+--------------+----------------+\\n\",\n      \"|      67HY0MW7|              12|\\n\",\n      \"|      R22O68FF|              98|\\n\",\n      \"|      J78AK31N|              81|\\n\",\n      \"|      8I9PRPGN|              41|\\n\",\n      \"|      4VHUTHOJ|               1|\\n\",\n      \"|      TMJ0OJ0B|              10|\\n\",\n      \"|      MD4PBMNN|              95|\\n\",\n      \"|      1XPVT5AY|              57|\\n\",\n      \"|      IH2QISS9|              94|\\n\",\n      \"|      7JJ73XCX|              61|\\n\",\n      \"|      T8QRTV6F|              10|\\n\",\n      \"|      C7NFUAR6|              65|\\n\",\n      \"|      NXRZZBVS|              52|\\n\",\n      \"|      H7ZQUWDJ|               9|\\n\",\n      \"|      YV47EGIC|              65|\\n\",\n      \"|      SC4LUMPZ|              53|\\n\",\n      \"|      ZES3NR0F|              89|\\n\",\n      \"|      KJ1JOOQ0|              13|\\n\",\n      \"|      ZHV68QKO|              89|\\n\",\n      \"|      4RE1ST7V|              22|\\n\",\n      \"|      8S4H8GNZ|              65|\\n\",\n      \"|      P007M3B8|             109|\\n\",\n      \"|      KI49INQW|              50|\\n\",\n      \"|      2NAKBIH8|              87|\\n\",\n      \"|      QRYFOK47|              36|\\n\",\n      \"|      3X1QOEBM|              68|\\n\",\n      \"|      TGYPRG6Y|              92|\\n\",\n      \"|      H8ONBK8M|              56|\\n\",\n      \"|      H0NRZ2VX|              22|\\n\",\n      \"|      NC7SHGMD|              71|\\n\",\n      \"+--------------+----------------+\\n\",\n      \"only showing top 30 rows\\n\",\n      \"\\n\",\n      \"6438\\n\",\n      \"+--------------+----------------+\\n\",\n      \"|opportunity_id|DaysTakenToClose|\\n\",\n      \"+--------------+----------------+\\n\",\n      \"|      67HY0MW7|              12|\\n\",\n      \"|      4VHUTHOJ|               1|\\n\",\n      \"|      TMJ0OJ0B|              10|\\n\",\n      \"|      T8QRTV6F|              10|\\n\",\n      \"|      H7ZQUWDJ|               9|\\n\",\n      \"|      KJ1JOOQ0|              13|\\n\",\n      \"|      4RE1ST7V|              22|\\n\",\n      \"|      H0NRZ2VX|              22|\\n\",\n      \"|      VB2E4FRU|               8|\\n\",\n      \"|      FLXHSKT4|              13|\\n\",\n      \"|      WHRDPR4H|              12|\\n\",\n      \"|      IF0LPAQA|              15|\\n\",\n      \"|      Z1L5OUDD|              12|\\n\",\n      \"|      NLKOGB9I|              18|\\n\",\n      \"|      MTEPBRDZ|               6|\\n\",\n      \"|      RVTAL02P|              11|\\n\",\n      \"|      4E73L1M3|              28|\\n\",\n      \"|      NASE5KTW|              12|\\n\",\n      \"|      LXTS18HY|               6|\\n\",\n      \"|      WA0B8VK9|              18|\\n\",\n      \"|      SPR1ZGYU|              30|\\n\",\n      \"|      L3BMFOAZ|               9|\\n\",\n      \"|      2CFS9GLC|              10|\\n\",\n      \"|      K1DFBO5B|              13|\\n\",\n      \"|      TRN9B8S9|               1|\\n\",\n      \"|      GCNZ7C5H|              13|\\n\",\n      \"|      ZWSHCZO3|              18|\\n\",\n      \"|      JEFB24SP|              18|\\n\",\n      \"|      9UXVO2DF|               7|\\n\",\n      \"|      WCP1FZLS|              10|\\n\",\n      \"+--------------+----------------+\\n\",\n      \"only showing top 30 rows\\n\",\n      \"\\n\",\n      \"2196\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"#Filter on deal_stage and parsing the date column to date type and using datediff\\n\",\n    \"result_prob3 = df_sales_pipeline.filter(col(\\\"deal_stage\\\")==\\\"Won\\\")\\\\\\n\",\n    \"                                .withColumn(\\\"DaysTakenToClose\\\", \\n\",\n    \"                                            datediff(to_date(\\\"close_date\\\",\\\"yyyy-MM-dd\\\"),\\n\",\n    \"                                                     to_date(\\\"created_on\\\",\\\"yyyy-MM-dd\\\"))).select(\\\"opportunity_id\\\",\\\"DaysTakenToClose\\\")\\n\",\n    \"result_prob3.show(30)\\n\",\n    \"print (result_prob3.count())\\n\",\n    \"\\n\",\n    \"#hardcoding the range of month as 30 for now\\n\",\n    \"result_prob3 = result_prob3.filter(col(\\\"DaysTakenToClose\\\") <= 30)\\n\",\n    \"result_prob3.show(30)\\n\",\n    \"print (result_prob3.count())\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 4: Display product(s) got maximum leads (by count) generated from paid source\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"#solution code here\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 5: Display 'Sales Agent' and 'Opportunity Count', for those sales agents who lost atleast two opportunties\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+------------------+----------------------+\\n\",\n      \"|       sales_agent|numOfLostOpportunities|\\n\",\n      \"+------------------+----------------------+\\n\",\n      \"|   Darcel Schlecht|                   337|\\n\",\n      \"|     Kami Bicknell|                   134|\\n\",\n      \"|    Vicki Laflamme|                   162|\\n\",\n      \"|      Elease Gluck|                    62|\\n\",\n      \"|Jonathan Berthelot|                   185|\\n\",\n      \"|   Daniell Hammack|                    80|\\n\",\n      \"|     Anna Snelling|                   140|\\n\",\n      \"|      Cassey Cress|                   137|\\n\",\n      \"|     Garret Kinder|                    63|\\n\",\n      \"|    Markita Hansen|                   115|\\n\",\n      \"|      Reed Clapper|                    87|\\n\",\n      \"|Rosie Papadopoulos|                    56|\\n\",\n      \"|   Maureen Marcano|                   119|\\n\",\n      \"|  Violet Mclelland|                   111|\\n\",\n      \"|  Gladys Colclough|                   149|\\n\",\n      \"|         Boris Faz|                    63|\\n\",\n      \"|    Wilburn Farren|                    44|\\n\",\n      \"| Versie Hillebrand|                   118|\\n\",\n      \"| Marty Freudenburg|                   120|\\n\",\n      \"|    Cecily Lampkin|                    86|\\n\",\n      \"+------------------+----------------------+\\n\",\n      \"only showing top 20 rows\\n\",\n      \"\\n\",\n      \"30\\n\",\n      \"+------------------+----------------------+\\n\",\n      \"|       sales_agent|numOfLostOpportunities|\\n\",\n      \"+------------------+----------------------+\\n\",\n      \"|   Darcel Schlecht|                   337|\\n\",\n      \"|     Kami Bicknell|                   134|\\n\",\n      \"|    Vicki Laflamme|                   162|\\n\",\n      \"|      Elease Gluck|                    62|\\n\",\n      \"|Jonathan Berthelot|                   185|\\n\",\n      \"|   Daniell Hammack|                    80|\\n\",\n      \"|     Anna Snelling|                   140|\\n\",\n      \"|      Cassey Cress|                   137|\\n\",\n      \"|     Garret Kinder|                    63|\\n\",\n      \"|    Markita Hansen|                   115|\\n\",\n      \"|      Reed Clapper|                    87|\\n\",\n      \"|Rosie Papadopoulos|                    56|\\n\",\n      \"|   Maureen Marcano|                   119|\\n\",\n      \"|  Violet Mclelland|                   111|\\n\",\n      \"|  Gladys Colclough|                   149|\\n\",\n      \"|         Boris Faz|                    63|\\n\",\n      \"|    Wilburn Farren|                    44|\\n\",\n      \"| Versie Hillebrand|                   118|\\n\",\n      \"| Marty Freudenburg|                   120|\\n\",\n      \"|    Cecily Lampkin|                    86|\\n\",\n      \"+------------------+----------------------+\\n\",\n      \"only showing top 20 rows\\n\",\n      \"\\n\",\n      \"30\\n\",\n      \"validation test:  True\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"result_prob5 = df_sales_pipeline.filter(col(\\\"deal_stage\\\")==\\\"Lost\\\")\\\\\\n\",\n    \"                                .select(\\\"sales_agent\\\",\\\"opportunity_id\\\")\\\\\\n\",\n    \"                                .groupBy(\\\"sales_agent\\\").agg(count(\\\"opportunity_id\\\").alias(\\\"numOfLostOpportunities\\\"))\\n\",\n    \"result_prob5.show(20)\\n\",\n    \"print (result_prob5.count())\\n\",\n    \"\\n\",\n    \"result_prob5 = result_prob5.filter(col(\\\"numOfLostOpportunities\\\") >= 2)\\n\",\n    \"\\n\",\n    \"result_prob5.show(20)\\n\",\n    \"print (result_prob5.count())\\n\",\n    \"\\n\",\n    \"#validation test\\n\",\n    \"print (\\\"validation test: \\\", result_prob5.agg(sum(\\\"numOfLostOpportunities\\\")).collect()[0][0] == df_sales_pipeline.filter(col(\\\"deal_stage\\\")==\\\"Lost\\\").count())\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 6: Display in ascending order of revenue, 'Account' and 'Revenue' for telecom accounts \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------------+-------+\\n\",\n      \"|             account|revenue|\\n\",\n      \"+--------------------+-------+\\n\",\n      \"|          Stanredtax|  14.79|\\n\",\n      \"|          Fasehatice|   19.2|\\n\",\n      \"|            Kan-code|  22.63|\\n\",\n      \"|           Treequote|   73.1|\\n\",\n      \"|           Konmatfix|  82.96|\\n\",\n      \"|Olivia Pope & Ass...|  97.94|\\n\",\n      \"|         Donquadtech| 110.88|\\n\",\n      \"|           Warephase| 130.62|\\n\",\n      \"|        Soylent Corp| 136.89|\\n\",\n      \"|         Iselectrics| 138.63|\\n\",\n      \"|              Yearin| 144.68|\\n\",\n      \"|           Ganjaflex|  161.8|\\n\",\n      \"|     Sterling Cooper| 204.47|\\n\",\n      \"|            Rangreen| 211.12|\\n\",\n      \"|            Xx-zobam| 221.86|\\n\",\n      \"|              Hatfan| 223.54|\\n\",\n      \"|            Betatech| 239.22|\\n\",\n      \"|           Duff Beer| 244.32|\\n\",\n      \"|         Good Burger| 247.91|\\n\",\n      \"|            Blackzim| 256.32|\\n\",\n      \"|             Nam-zim| 369.58|\\n\",\n      \"|         Krusty Krab| 372.21|\\n\",\n      \"|               Hooli| 374.84|\\n\",\n      \"|             Finhigh| 398.18|\\n\",\n      \"|            Hottechi|  431.1|\\n\",\n      \"|          Bubba Gump| 459.79|\\n\",\n      \"|          Green-Plus| 562.28|\\n\",\n      \"|              Sonron| 588.46|\\n\",\n      \"|             Codehow| 638.03|\\n\",\n      \"|          Lexiqvolax| 652.53|\\n\",\n      \"+--------------------+-------+\\n\",\n      \"only showing top 30 rows\\n\",\n      \"\\n\",\n      \"97\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"df_accounts = df_accounts.withColumn(\\\"revenue\\\",df_accounts[\\\"revenue\\\"].cast(DoubleType()))\\n\",\n    \"result_prob6 = df_accounts.orderBy(\\\"revenue\\\",ascending=True).select(\\\"account\\\",\\\"revenue\\\")\\n\",\n    \"result_prob6.show(30)\\n\",\n    \"print (result_prob6.count())\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 7: Display by revenue generated, bottom five 'Industries' and 'Revenue'\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+-----------------+-------+\\n\",\n      \"|          account|revenue|\\n\",\n      \"+-----------------+-------+\\n\",\n      \"|   Dalttechnology| 6085.6|\\n\",\n      \"|            Silis|5339.57|\\n\",\n      \"|            Newex|5093.78|\\n\",\n      \"| Wonka Industries|4962.27|\\n\",\n      \"|         Faxquote|4939.54|\\n\",\n      \"|       Sunnamplex|4592.96|\\n\",\n      \"|            Isdom|4514.68|\\n\",\n      \"|          Golddex|4340.32|\\n\",\n      \"|          Conecom|4242.85|\\n\",\n      \"| Stark Industries|4221.65|\\n\",\n      \"|         Scotfind|3911.27|\\n\",\n      \"|         Ron-tech|3805.02|\\n\",\n      \"|         Gogozoom| 3577.1|\\n\",\n      \"|       Bioholding| 3321.9|\\n\",\n      \"|         Zumgoity| 3264.4|\\n\",\n      \"|Wayne Enterprises|3193.45|\\n\",\n      \"|         Dontechi|2990.17|\\n\",\n      \"|       Gekko & Co|2934.79|\\n\",\n      \"|       Zathunicon|2913.82|\\n\",\n      \"|         Labdrill|2913.26|\\n\",\n      \"+-----------------+-------+\\n\",\n      \"only showing top 20 rows\\n\",\n      \"\\n\",\n      \"97\\n\",\n      \"+----------+-------+\\n\",\n      \"|   account|revenue|\\n\",\n      \"+----------+-------+\\n\",\n      \"|Stanredtax|  14.79|\\n\",\n      \"|Fasehatice|   19.2|\\n\",\n      \"|  Kan-code|  22.63|\\n\",\n      \"| Treequote|   73.1|\\n\",\n      \"| Konmatfix|  82.96|\\n\",\n      \"+----------+-------+\\n\",\n      \"only showing top 5 rows\\n\",\n      \"\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"result_prob7 = df_accounts.orderBy(\\\"revenue\\\",ascending=False).select(\\\"account\\\",\\\"revenue\\\")\\n\",\n    \"result_prob7.show(20)\\n\",\n    \"print (result_prob7.count())\\n\",\n    \"#generating id incrementally for accounts sorted by revenue in decreasing order\\n\",\n    \"result_prob7 = result_prob7.withColumn(\\\"index\\\", monotonically_increasing_id())\\n\",\n    \"#sorting by index in descending order so that we get accounts with least revenue (bottom 5)\\n\",\n    \"result_prob7.orderBy(desc(\\\"index\\\")).drop(\\\"index\\\").show(5)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 8: Display 'Month of Year' vs 'Sales', for GTXBasic. NOTE: \\\"Month of Year\\\" means month year (eg. Jan) and \\\"Month\\\" means month (eg. Jan 2020, Jan 2021 etc)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------+-----------+--------+----------+----------+-------------+\\n\",\n      \"|opportunity_id| deal_stage| product|created_on|close_date|Month Of year|\\n\",\n      \"+--------------+-----------+--------+----------+----------+-------------+\\n\",\n      \"|      67HY0MW7|        Won|GTXBasic|2017-04-24|2017-05-06|     Apr 2017|\\n\",\n      \"|      BRL1KVVH|       Lost|GTXBasic|2017-05-19|2017-08-03|     May 2017|\\n\",\n      \"|      R22O68FF|        Won|GTXBasic|2017-03-21|2017-06-27|     Mar 2017|\\n\",\n      \"|      TMJ0OJ0B|        Won|GTXBasic|2017-06-30|2017-07-10|     Jun 2017|\\n\",\n      \"|      B22V5Z3B|       Lost|GTXBasic|2017-07-25|2017-08-07|     Jul 2017|\\n\",\n      \"|      H7ZQUWDJ|        Won|GTXBasic|2017-12-21|2017-12-30|     Dec 2017|\\n\",\n      \"|      HC77MZU1|       Lost|GTXBasic|2017-07-25|2017-09-07|     Jul 2017|\\n\",\n      \"|      27QUC5M7|In_Progress|GTXBasic|2017-11-01|      null|     Nov 2017|\\n\",\n      \"|      N3DXP5OP|In_Progress|GTXBasic|2017-02-05|      null|     Feb 2017|\\n\",\n      \"|      ZLLF7UHU|       Lost|GTXBasic|2017-09-20|2017-12-08|     Sep 2017|\\n\",\n      \"|      QRYFOK47|        Won|GTXBasic|2017-03-27|2017-05-02|     Mar 2017|\\n\",\n      \"|      QCA1IIKF|In_Progress|GTXBasic|2016-11-25|      null|     Nov 2016|\\n\",\n      \"|      P0I0DTBJ|       Lost|GTXBasic|2017-02-15|2017-04-04|     Feb 2017|\\n\",\n      \"|      5S5DO3QC|       Lost|GTXBasic|2017-01-08|2017-04-03|     Jan 2017|\\n\",\n      \"|      8QSPOR0V|       Lost|GTXBasic|2017-08-09|2017-09-12|     Aug 2017|\\n\",\n      \"|      WHRDPR4H|        Won|GTXBasic|2017-10-19|2017-10-31|     Oct 2017|\\n\",\n      \"|      V34SNG4P|In_Progress|GTXBasic|2017-10-04|      null|     Oct 2017|\\n\",\n      \"|      DNTUK4O1|In_Progress|GTXBasic|2017-05-21|      null|     May 2017|\\n\",\n      \"|      77VRR78O|       Lost|GTXBasic|2017-06-21|2017-09-06|     Jun 2017|\\n\",\n      \"|      E9JHZR7J|        Won|GTXBasic|2017-10-27|2017-12-16|     Oct 2017|\\n\",\n      \"|      9L5HPLM6|        Won|GTXBasic|2017-06-22|2017-10-02|     Jun 2017|\\n\",\n      \"|      OL2RFQCM|        Won|GTXBasic|2017-06-20|2017-08-16|     Jun 2017|\\n\",\n      \"|      377G0K33|       Lost|GTXBasic|2017-10-23|2017-10-25|     Oct 2017|\\n\",\n      \"|      Y131Y9KM|In_Progress|GTXBasic|2017-03-10|      null|     Mar 2017|\\n\",\n      \"|      NEJZ68R1|       Lost|GTXBasic|2017-07-02|2017-07-07|     Jul 2017|\\n\",\n      \"|      FOSIPD0U|In_Progress|GTXBasic|2017-09-17|      null|     Sep 2017|\\n\",\n      \"|      JYYU4CDI|In_Progress|GTXBasic|2017-06-25|      null|     Jun 2017|\\n\",\n      \"|      6RNOFZRB|In_Progress|GTXBasic|2017-10-21|      null|     Oct 2017|\\n\",\n      \"|      NFNYO1WJ|        Won|GTXBasic|2017-08-07|2017-09-11|     Aug 2017|\\n\",\n      \"|      BQ91O7T3|        Won|GTXBasic|2017-05-13|2017-07-03|     May 2017|\\n\",\n      \"+--------------+-----------+--------+----------+----------+-------------+\\n\",\n      \"only showing top 30 rows\\n\",\n      \"\\n\",\n      \"3062\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"#formatting created_on (sales initiation date)\\n\",\n    \"result_prob8 = df_sales_pipeline.filter(col(\\\"product\\\")=='GTXBasic')\\\\\\n\",\n    \"                                .select(\\\"opportunity_id\\\",\\\"deal_stage\\\",\\\"product\\\",\\\"created_on\\\",\\\"close_date\\\")\\\\\\n\",\n    \"                                .withColumn(\\\"Month Of year\\\",date_format(\\\"created_on\\\",\\\"LLL y\\\"))\\n\",\n    \"result_prob8.show(30)\\n\",\n    \"print (result_prob8.count())\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 9: Which sales agent(s) never lost a deal. Display as a dictionary {sales agent:sales}\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"dict_keys(['Donn Cantrell', 'James Ascencio', 'Niesha Huffines', 'Kami Bicknell', 'Versie Hillebrand', 'Kary Hendrixson', 'Anna Snelling', 'Vicki Laflamme', 'Darcel Schlecht', 'Marty Freudenburg', 'Lajuana Vencill', 'Reed Clapper', 'Elease Gluck', 'Rosie Papadopoulos', 'Jonathan Berthelot', 'Zane Levy', 'Rosalina Dieter', 'Cecily Lampkin', 'Gladys Colclough', 'Daniell Hammack', 'Moses Frase', 'Wilburn Farren', 'Violet Mclelland', 'Markita Hansen', 'Corliss Cosme', 'Cassey Cress', 'Boris Faz', 'Maureen Marcano', 'Hayden Neloms', 'Garret Kinder'])\\n\",\n      \"30\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"df_sales_notlost = df_sales_pipeline.filter(col(\\\"deal_stage\\\") != \\\"Lost\\\").select(\\\"opportunity_id\\\",\\\"sales_agent\\\",\\\"close_value\\\")\\n\",\n    \"result_prob9 = defaultdict(list)\\n\",\n    \"for row in df_sales_notlost.toJSON().collect():\\n\",\n    \"    row_json = json.loads(row)\\n\",\n    \"    if \\\"close_value\\\" in row_json:\\n\",\n    \"        result_prob9[row_json['sales_agent']].append({\\\"opportunity_id\\\":row_json['opportunity_id'],\\n\",\n    \"                                                      \\\"close_value\\\":row_json[\\\"close_value\\\"]})\\n\",\n    \"    else:\\n\",\n    \"        result_prob9[row_json['sales_agent']].append({\\\"opportunity_id\\\":row_json['opportunity_id'],\\n\",\n    \"                                                      \\\"close_value\\\":None})\\n\",\n    \"print (result_prob9.keys())\\n\",\n    \"print (len(result_prob9.keys()))\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 10: Display 'Sales Agents', 'Product', and 'Sales', for those sales agents who closed more than one deal on same day\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------+-----------------+------------+----------------+\\n\",\n      \"|opportunity_id|      sales_agent|     product|DaysTakenToClose|\\n\",\n      \"+--------------+-----------------+------------+----------------+\\n\",\n      \"|      67HY0MW7|    Donn Cantrell|    GTXBasic|              12|\\n\",\n      \"|      R22O68FF|  Niesha Huffines|    GTXBasic|              98|\\n\",\n      \"|      J78AK31N|    Kami Bicknell|      MGRPFU|              81|\\n\",\n      \"|      8I9PRPGN|Versie Hillebrand|      MGRPFS|              41|\\n\",\n      \"|      4VHUTHOJ|    Kami Bicknell|GTXPlusBasic|               1|\\n\",\n      \"|      TMJ0OJ0B|  Kary Hendrixson|    GTXBasic|              10|\\n\",\n      \"|      MD4PBMNN|    Anna Snelling|      MGRPFU|              95|\\n\",\n      \"|      1XPVT5AY|  Kary Hendrixson|  GTXPlusPro|              57|\\n\",\n      \"|      IH2QISS9|  Kary Hendrixson|      GTXPro|              94|\\n\",\n      \"|      7JJ73XCX|   James Ascencio|GTXPlusBasic|              61|\\n\",\n      \"|      T8QRTV6F|   James Ascencio|  GTXPlusPro|              10|\\n\",\n      \"|      C7NFUAR6|Marty Freudenburg|GTXPlusBasic|              65|\\n\",\n      \"|      NXRZZBVS|  Lajuana Vencill|      MGRPFU|              52|\\n\",\n      \"|      H7ZQUWDJ|     Reed Clapper|    GTXBasic|               9|\\n\",\n      \"|      YV47EGIC|    Anna Snelling|      MGRPFS|              65|\\n\",\n      \"|      SC4LUMPZ|     Elease Gluck|      MGRPFS|              53|\\n\",\n      \"|      ZES3NR0F|Versie Hillebrand|      MGRPFS|              89|\\n\",\n      \"|      KJ1JOOQ0|  Niesha Huffines|      MGRPFS|              13|\\n\",\n      \"|      ZHV68QKO|     Reed Clapper|      GTXPro|              89|\\n\",\n      \"|      4RE1ST7V|    Kami Bicknell|  GTXPlusPro|              22|\\n\",\n      \"+--------------+-----------------+------------+----------------+\\n\",\n      \"only showing top 20 rows\\n\",\n      \"\\n\",\n      \"6438\\n\",\n      \"+------------------+------------+-----------------------+\\n\",\n      \"|       sales_agent|     product|completed_opportunities|\\n\",\n      \"+------------------+------------+-----------------------+\\n\",\n      \"|    Markita Hansen|GTXPlusBasic|                      2|\\n\",\n      \"|   Darcel Schlecht|      GTXPro|                      2|\\n\",\n      \"| Marty Freudenburg|    GTXBasic|                      2|\\n\",\n      \"|     Kami Bicknell|GTXPlusBasic|                      2|\\n\",\n      \"|  Gladys Colclough|GTXPlusBasic|                      2|\\n\",\n      \"|   Darcel Schlecht|      MGRPFS|                      2|\\n\",\n      \"|   Darcel Schlecht|GTXPlusBasic|                      2|\\n\",\n      \"|Jonathan Berthelot|    GTXBasic|                      6|\\n\",\n      \"|       Moses Frase|    GTXBasic|                      2|\\n\",\n      \"|     Kami Bicknell|    GTXBasic|                      2|\\n\",\n      \"|      Cassey Cress|    GTXBasic|                      2|\\n\",\n      \"|Rosie Papadopoulos|    GTXBasic|                      2|\\n\",\n      \"|     Anna Snelling|  GTXPlusPro|                      3|\\n\",\n      \"|   Kary Hendrixson|    GTXBasic|                      2|\\n\",\n      \"+------------------+------------+-----------------------+\\n\",\n      \"\\n\",\n      \"14\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"result_prob10 = df_sales_pipeline.filter(col(\\\"deal_stage\\\")==\\\"Won\\\")\\\\\\n\",\n    \"                                 .withColumn(\\\"DaysTakenToClose\\\", \\n\",\n    \"                                            datediff(to_date(\\\"close_date\\\",\\\"yyyy-MM-dd\\\"),\\n\",\n    \"                                                     to_date(\\\"created_on\\\",\\\"yyyy-MM-dd\\\")))\\\\\\n\",\n    \"                                 .select(\\\"opportunity_id\\\",\\\"sales_agent\\\",\\\"product\\\",\\\"DaysTakenToClose\\\")\\n\",\n    \"\\n\",\n    \"result_prob10.show(20)\\n\",\n    \"print (result_prob10.count())\\n\",\n    \"result_prob10 = result_prob10.filter(col(\\\"DaysTakenToClose\\\") == 1)\\\\\\n\",\n    \"                             .select(\\\"sales_agent\\\",\\\"product\\\",\\\"opportunity_id\\\")\\\\\\n\",\n    \"                             .groupBy(\\\"sales_agent\\\",\\\"product\\\").agg(count(\\\"opportunity_id\\\").alias(\\\"completed_opportunities\\\"))\\\\\\n\",\n    \"                             .filter(col(\\\"completed_opportunities\\\") > 1)\\n\",\n    \"\\n\",\n    \"result_prob10.show(20)\\n\",\n    \"print (result_prob10.count())\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Refer & Use Orchestra.json to answer problem 11-13 below\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 11: Display the instrument played by Lehmann Caroline\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------------+--------------------+--------------------+---------+-------+--------------------+\\n\",\n      \"|            concerts|                  id|           orchestra|programID| season|               works|\\n\",\n      \"+--------------------+--------------------+--------------------+---------+-------+--------------------+\\n\",\n      \"|[{1842-12-07T05:0...|00646b9f-fec7-4ff...|New York Philharm...|     3853|1842-43|[{52446*, Beethov...|\\n\",\n      \"|[{1843-02-18T05:0...|1118e84e-eb59-46c...|New York Philharm...|     5178|1842-43|[{52437*, Beethov...|\\n\",\n      \"|[{1843-04-07T05:0...|08536612-27c3-437...|Musicians from th...|    10785|1842-43|[{52364*1, Beetho...|\\n\",\n      \"|[{1843-04-22T05:0...|81a3b8de-1737-4c9...|New York Philharm...|     5887|1842-43|[{52434*, Beethov...|\\n\",\n      \"|[{1843-11-18T05:0...|09581bb7-8855-496...|New York Philharm...|      305|1843-44|[{52453*, Beethov...|\\n\",\n      \"|[{1844-01-13T05:0...|0848266c-8eee-48a...|New York Philharm...|     3368|1843-44|[{51668*, Mozart,...|\\n\",\n      \"|[{1844-03-16T05:0...|8025e763-9c12-415...|New York Philharm...|     4226|1843-44|[{3707*, Spohr,  ...|\\n\",\n      \"|[{1844-05-18T05:0...|19d44866-ee7b-48d...|New York Philharm...|     5087|1843-44|[{52446*, Beethov...|\\n\",\n      \"|[{1844-11-16T05:0...|4f13ab38-9eb4-414...|New York Philharm...|     6310|1844-45|[{52456*, Beethov...|\\n\",\n      \"|[{1845-01-11T05:0...|7725e2f7-7f77-41d...|New York Philharm...|     1979|1844-45|[{51727*, Haydn, ...|\\n\",\n      \"|[{1845-03-01T05:0...|f1de3488-6831-408...|New York Philharm...|     2821|1844-45|[{52437*, Beethov...|\\n\",\n      \"|[{1845-04-19T05:0...|cd444e18-1fcd-4d6...|New York Philharm...|     3259|1844-45|[{52453*, Beethov...|\\n\",\n      \"|[{1845-11-22T05:0...|51ee4702-8f57-4fe...|New York Philharm...|     4919|1845-46|[{52575*, Mendels...|\\n\",\n      \"|[{1846-01-17T05:0...|1b162182-4605-4cb...|New York Philharm...|      562|1845-46|[{52446*, Beethov...|\\n\",\n      \"|[{1846-03-07T05:0...|66cc492e-e6eb-42e...|New York Philharm...|     1408|1845-46|[{3826*, Kalliwod...|\\n\",\n      \"|[{1846-04-25T05:0...|08205151-c17b-4de...|New York Philharm...|     1851|1845-46|[{51664*, Mozart,...|\\n\",\n      \"|[{1846-05-20T05:0...|079d4d73-e2e7-4c8...|New York Philharm...|     2321|1845-46|[{6709*16, Weber,...|\\n\",\n      \"|[{1846-11-21T05:0...|f679abf1-6beb-408...|New York Philharm...|     3540|1846-47|[{3864*, Spohr,  ...|\\n\",\n      \"|[{1847-01-09T05:0...|111c22e5-0527-4e1...|New York Philharm...|     6573|1846-47|[{51658*, Mozart,...|\\n\",\n      \"|[{1847-03-06T05:0...|07ffca52-b177-43c...|New York Philharm...|       47|1846-47|[{52453*, Beethov...|\\n\",\n      \"+--------------------+--------------------+--------------------+---------+-------+--------------------+\\n\",\n      \"only showing top 20 rows\\n\",\n      \"\\n\",\n      \"1033\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"#Edited the orchestra.json file to retrieve the proper JSON structure to accommodate Array of JSON objects\\n\",\n    \"df_orchestra = spark.read.format(\\\"json\\\").option(\\\"multiline\\\",\\\"true\\\").load(\\\"data/Orchestra.json\\\")\\n\",\n    \"df_orchestra.show(20)\\n\",\n    \"print (df_orchestra.count())\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[('concerts',\\n\",\n       \"  'array<struct<Date:string,Location:string,Time:string,Venue:string,eventType:string>>'),\\n\",\n       \" ('id', 'string'),\\n\",\n       \" ('orchestra', 'string'),\\n\",\n       \" ('programID', 'string'),\\n\",\n       \" ('season', 'string'),\\n\",\n       \" ('works',\\n\",\n       \"  'array<struct<ID:string,composerName:string,conductorName:string,interval:string,movement:string,soloists:array<struct<soloistInstrument:string,soloistName:string,soloistRoles:string>>,workTitle:string>>')]\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"df_orchestra.dtypes\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def getRequiredInstrument(ws,soloist_name):\\n\",\n    \"    exists = None\\n\",\n    \"    for work in ws:\\n\",\n    \"        if len(work['soloists']) > 0:\\n\",\n    \"            for soloist_element in work['soloists']:\\n\",\n    \"                if soloist_element[\\\"soloistName\\\"] == soloist_name:\\n\",\n    \"                    exists = 1\\n\",\n    \"                    break\\n\",\n    \"            if exists == 1:\\n\",\n    \"                break\\n\",\n    \"        else:\\n\",\n    \"            continue\\n\",\n    \"    if exists:\\n\",\n    \"        return soloist_element[\\\"soloistInstrument\\\"]\\n\",\n    \"    else:\\n\",\n    \"        return \\\"\\\"\\n\",\n    \"\\n\",\n    \"instrumentUDF = udf(lambda colname,sname: getRequiredInstrument(colname,sname))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 18,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------------+--------------------+--------------------+---------+-----------------+\\n\",\n      \"|                  id|           orchestra|               works|programID|return_instrument|\\n\",\n      \"+--------------------+--------------------+--------------------+---------+-----------------+\\n\",\n      \"|21b49b4a-1805-41b...|New York Philharm...|[{52437*, Beethov...|     5792|          Soprano|\\n\",\n      \"|89c1db0d-8c41-476...|New York Philharm...|[{52577*, Mendels...|     2149|          Soprano|\\n\",\n      \"|4e81347f-898d-48b...|New York Philharm...|[{52374*1, Cherub...|     6613|          Soprano|\\n\",\n      \"+--------------------+--------------------+--------------------+---------+-----------------+\\n\",\n      \"\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"test = df_orchestra.withColumn(\\\"return_instrument\\\",instrumentUDF(\\\"works\\\",lit(\\\"Lehmann, Caroline\\\")))\\n\",\n    \"test.select(\\\"id\\\",\\\"orchestra\\\",\\\"works\\\",\\\"programID\\\",\\\"return_instrument\\\").filter(col(\\\"return_instrument\\\")!=\\\"\\\").show(40)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 12: Display all vocalists\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 19,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"[Row(composerName=['Beethoven,  Ludwig  van', 'Weber,  Carl  Maria Von', 'Hummel,  Johann', 'Pacini,  Giovanni', 'Romberg,  Bernhard', 'Onslow,  George', 'Onslow,  George', 'Rossini,  Gioachino', 'Thalberg,  Sigismond', 'Mozart,  Wolfgang  Amadeus', 'Herz,  Henri', 'Lindpaintner,  Peter  Von']),\\n\",\n       \" Row(composerName=['Beethoven,  Ludwig  van', 'Vieuxtemps,  Henri', 'Mendelssohn,  Felix', 'Donizetti,  Gaetano', 'Weber,  Carl  Maria Von']),\\n\",\n       \" Row(composerName=['Beethoven,  Ludwig  van', None, 'Loder,  George, Jr.', 'Mendelssohn,  Felix', 'Lindpaintner,  Peter  Von', 'Beriot,  Charles-Auguste  de', 'Reissiger,  Karl  Gottlieb']),\\n\",\n       \" Row(composerName=['Schumann,  Robert', 'Haydn,  Franz  Joseph', 'Ernst,  Heinrich  Wilhelm', None, 'Rietz,  Julius', 'Weber,  Carl  Maria Von', 'Mollenhauer,  Friedrich', None, 'Beethoven,  Ludwig  van']),\\n\",\n       \" Row(composerName=['Strauss,  Richard', 'Beethoven,  Ludwig  van', None, 'Volkmann,  Friedrich  Robert', 'Schumann,  Robert']),\\n\",\n       \" Row(composerName=['Wagner,  Richard', 'Rubinstein,  Anton', 'Joachim,  Joseph', None, 'Beethoven,  Ludwig  van']),\\n\",\n       \" Row(composerName=['Wagner,  Richard', 'Wagner,  Richard', 'Schubert,  Franz', None, 'Tchaikovsky,  Pyotr  Ilyich']),\\n\",\n       \" Row(composerName=['Wagner,  Richard', 'Godard,  Benjamin', 'Svendsen,  Johan', 'Beethoven,  Ludwig  van', 'Beethoven,  Ludwig  van', 'Delibes,  Léo', 'Delibes,  Léo', None, 'Beethoven,  Ludwig  van', 'Wagner,  Richard', 'Arditi,  Luigi', 'Schenck,  Elliott', 'Schenck,  Elliott', 'Ziehrer,  Carl  Michael']),\\n\",\n       \" Row(composerName=['Bulow,  Hans  Von', 'Brahms,  Johannes', 'Verdi,  Giuseppe', 'Verdi,  Giuseppe', 'Liszt,  Franz', 'Pfeffer,  Walter', None, 'Beethoven,  Ludwig  van']),\\n\",\n       \" Row(composerName=['Schumann,  Robert', 'Saint-Saens [Saint-Saëns],  Camille', None, 'Wagner,  Richard', 'Wagner,  Richard', 'Wagner,  Richard', 'Wagner,  Richard', 'Beethoven,  Ludwig  van'])]\"\n      ]\n     },\n     \"execution_count\": 19,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"df_orchestra.select(\\\"works.composerName\\\").distinct().take(10)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 13: Display orchestra played under program id 2561\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 20,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+---------+--------------------+\\n\",\n      \"|programID|           orchestra|\\n\",\n      \"+---------+--------------------+\\n\",\n      \"|     2561|New York Philharm...|\\n\",\n      \"+---------+--------------------+\\n\",\n      \"\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"df_orchestra.select(\\\"programID\\\",\\\"orchestra\\\").filter(col(\\\"programID\\\")==\\\"2561\\\").show()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Refer & Use Orchestra.xml to answer problem 14-15 below\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 14: Display locations used for event at time 8:15 PM\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 21,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"def get_locations(concerts,time):\\n\",\n    \"    locations = []\\n\",\n    \"    if len(concerts) > 0:\\n\",\n    \"        for concert in concerts:\\n\",\n    \"            if concert['Time'] == '8:15PM':\\n\",\n    \"                locations.append(concert['Location'])\\n\",\n    \"    if len(locations) > 0:\\n\",\n    \"        return locations\\n\",\n    \"    else:\\n\",\n    \"        return \\\"\\\"\\n\",\n    \"\\n\",\n    \"locationsUDF = udf(lambda colname,sname: get_locations(colname,sname))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 22,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------------+--------------------+--------------------+---------+---------------+\\n\",\n      \"|                  id|           orchestra|            concerts|programID|return_location|\\n\",\n      \"+--------------------+--------------------+--------------------+---------+---------------+\\n\",\n      \"|1124c816-f97c-4cf...|   New York Symphony|[{1888-12-28T05:0...|    11610|[Manhattan, NY]|\\n\",\n      \"|7e1d590a-9750-4e0...|   New York Symphony|[{1889-12-13T05:0...|     7921|[Manhattan, NY]|\\n\",\n      \"|ebe38ed5-af8a-42c...|   New York Symphony|[{1890-01-31T05:0...|     8072|[Manhattan, NY]|\\n\",\n      \"|fa51a57c-f27c-430...|   New York Symphony|[{1891-11-17T05:0...|    14304|[Manhattan, NY]|\\n\",\n      \"|20df0162-d9ad-407...|   New York Symphony|[{1891-11-19T05:0...|    14305|[Manhattan, NY]|\\n\",\n      \"|c5f00d41-3ae7-499...|   New York Symphony|[{1892-01-15T05:0...|     8087|[Manhattan, NY]|\\n\",\n      \"|de6b31a7-d117-47e...|   New York Symphony|[{1892-02-05T05:0...|     8088|[Manhattan, NY]|\\n\",\n      \"|637c6a11-0e03-48c...|   New York Symphony|[{1892-03-04T05:0...|     8089|[Manhattan, NY]|\\n\",\n      \"|d617e80c-a31a-415...|   New York Symphony|[{1892-04-01T05:0...|     8090|[Manhattan, NY]|\\n\",\n      \"|d37f0df9-9e87-477...|Members of NY Phi...|[{1892-10-21T05:0...|     9742|[Manhattan, NY]|\\n\",\n      \"|58aa553d-b941-4b9...|   New York Symphony|[{1892-11-11T05:0...|     8091|[Manhattan, NY]|\\n\",\n      \"|55d5fc26-abb2-409...|   New York Symphony|[{1892-12-02T05:0...|     8092|[Manhattan, NY]|\\n\",\n      \"|384caf29-6ebc-40b...|New York Philharm...|[{1892-12-16T05:0...|     6073|[Manhattan, NY]|\\n\",\n      \"|2678ff7b-ecfa-4c7...|   New York Symphony|[{1893-01-06T05:0...|     8093|[Manhattan, NY]|\\n\",\n      \"|43599c50-2a7d-40d...|New York Philharm...|[{1893-01-13T05:0...|     2391|[Manhattan, NY]|\\n\",\n      \"|e39ec35e-ab4e-41f...|   New York Symphony|[{1893-02-03T05:0...|     8104|[Manhattan, NY]|\\n\",\n      \"|9786f71d-9e46-405...|New York Philharm...|[{1893-02-10T05:0...|     6730|[Manhattan, NY]|\\n\",\n      \"|61de5748-841a-428...|New York Philharm...|[{1893-03-03T05:0...|     3710|[Manhattan, NY]|\\n\",\n      \"|a9501082-5d8e-449...|   New York Symphony|[{1893-03-10T05:0...|     8105|[Manhattan, NY]|\\n\",\n      \"|66cd0517-a1d9-4b1...|New York Philharm...|[{1893-03-24T05:0...|     3714|[Manhattan, NY]|\\n\",\n      \"|a8f7f5ce-cb62-4db...|   New York Symphony|[{1893-11-10T05:0...|     8107|[Manhattan, NY]|\\n\",\n      \"|0c851376-a2b2-4a7...|New York Philharm...|[{1893-11-17T05:0...|     2589|[Manhattan, NY]|\\n\",\n      \"|e02e6ffd-4071-451...|   New York Symphony|[{1893-11-19T05:0...|     9741|[Manhattan, NY]|\\n\",\n      \"|f61c75a0-7355-4a2...|   New York Symphony|[{1893-12-08T05:0...|     8108|[Manhattan, NY]|\\n\",\n      \"|489b901d-bd34-40c...|New York Philharm...|[{1893-12-15T05:0...|     6924|[Manhattan, NY]|\\n\",\n      \"|324d6827-eabb-41e...|   New York Symphony|[{1894-01-05T05:0...|     8109|[Manhattan, NY]|\\n\",\n      \"|50fcb7b0-f8e7-407...|New York Philharm...|[{1894-01-12T05:0...|     3280|[Manhattan, NY]|\\n\",\n      \"|f439468c-ee5b-43a...|New York Philharm...|[{1894-02-09T05:0...|      252|[Manhattan, NY]|\\n\",\n      \"|d16b069c-3509-454...|New York Philharm...|[{1894-03-09T05:0...|     4619|[Manhattan, NY]|\\n\",\n      \"|3bbe1795-301b-4a3...|   New York Symphony|[{1894-03-16T05:0...|     8112|[Manhattan, NY]|\\n\",\n      \"|c5ccb40c-2863-4c2...|New York Philharm...|[{1894-04-06T05:0...|     1598|[Manhattan, NY]|\\n\",\n      \"|f5c265a2-e66d-4a0...|   New York Symphony|[{1894-11-09T05:0...|     8113|[Manhattan, NY]|\\n\",\n      \"|4dba2644-4271-43e...|New York Philharm...|[{1894-11-16T05:0...|     3497|[Manhattan, NY]|\\n\",\n      \"|3e41efc1-0f56-494...|   New York Symphony|[{1894-12-07T05:0...|     8114|[Manhattan, NY]|\\n\",\n      \"|6ad4c55c-ec61-41a...|New York Philharm...|[{1894-12-14T05:0...|      435|[Manhattan, NY]|\\n\",\n      \"|eb3ed63a-6b27-449...|   New York Symphony|[{1894-12-29T05:0...|    11624|[Manhattan, NY]|\\n\",\n      \"|6587d4bd-e471-4c3...|   New York Symphony|[{1895-01-04T05:0...|     8115|[Manhattan, NY]|\\n\",\n      \"|2fadbd45-5e46-482...|   New York Symphony|[{1895-01-06T05:0...|    10576|[Manhattan, NY]|\\n\",\n      \"|eb47e326-1219-466...|New York Philharm...|[{1895-01-11T05:0...|     4191|[Manhattan, NY]|\\n\",\n      \"|a51c295b-e56d-4a3...|   New York Symphony|[{1895-02-01T05:0...|     8118|[Manhattan, NY]|\\n\",\n      \"+--------------------+--------------------+--------------------+---------+---------------+\\n\",\n      \"only showing top 40 rows\\n\",\n      \"\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"test = df_orchestra.withColumn(\\\"return_location\\\",locationsUDF(\\\"concerts\\\",lit(\\\"8:15PM\\\")))\\n\",\n    \"test.select(\\\"id\\\",\\\"orchestra\\\",\\\"concerts\\\",\\\"programID\\\",\\\"return_location\\\").filter(col(\\\"return_location\\\")!=\\\"\\\").show(40)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 23,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"+--------------------+\\n\",\n      \"|     return_location|\\n\",\n      \"+--------------------+\\n\",\n      \"|   [Springfield, MA]|\\n\",\n      \"|        [Newark, NJ]|\\n\",\n      \"|     [Manhattan, NY]|\\n\",\n      \"|    [Providence, RI]|\\n\",\n      \"|  [Indianapolis, IN]|\\n\",\n      \"|     [New Haven, CT]|\\n\",\n      \"|      [Brooklyn, NY]|\\n\",\n      \"|  [Philadelphia, PA]|\\n\",\n      \"|      [Hartford, CT]|\\n\",\n      \"|[Manhattan, NY, B...|\\n\",\n      \"|[Manhattan, NY, M...|\\n\",\n      \"+--------------------+\\n\",\n      \"\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"test.filter(col(\\\"return_location\\\")!=\\\"\\\").select(\\\"return_location\\\").distinct().show(40)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"PROBLEM 15: Display total number of programs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 24,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/plain\": [\n       \"1033\"\n      ]\n     },\n     \"execution_count\": 24,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"#solution code here\\n\",\n    \"df_orchestra.count()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"********************************************* Test ends here **************************************************\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.8.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"
  },
  {
    "path": "Byndr/README.md",
    "content": "# Interview Experience for Data Engineer (Big Data) - 2021:  \n### First Round:  \n+ What is Hive?  \n+ What is Hive metastore?  \n+ Hive external table vs managed table.  \n+ evalute Programming skills - one question on that.  \n+ mappers and reducers in Spark execution flow.  \n+ what are `groupByKey` and `reduceByKey` operations in Spark.  \n+ Write spark skeleton code for given scenario - reading a CSV and do some transformations on it - Code doesn't have to be exact but steps matter.  \n+ Given a requirement (find the second largest value of a column for every value of other column - Window functions in SQL), what are the steps to achieve it using only spark-sql without dataframes/RDDs API in spark?\n+ Questions on SQL for window functions in spark (SQL query is preferred compared to Dataframes API).  \n+ Different storage formats in big data space? questions on that (`parquet`, `CSV`, `JSON`, `avro`, `delta` etc).  \n+ Questions on Hadoop ecosystem if any.  \n"
  },
  {
    "path": "CloudCover/README.md",
    "content": "# Personal Experience for Data Engineer - 2021:  \n## First round:  \nLive Programming round - Given 1.5 hrs of time, you need to solve a problem statement live on web based IDE.  \n  \n## Second round:  \nTechical Discussion on the projects done, Some interview questions on Spark,Hive,Hadoop:  \n   - About windows functions in spark, what they are used for in spark?\n   - About UDFs in spark and how they are different from normal spark functions in performance.  \n   - Difference between external table and managed table in hive.  \n   - experience on moving large scale data between different sinks? cloud migrations? database migrations?  \n   - experience writing complex sql queries?  \n   - behaviorial questions.  \n   - current project and what are the responsibilities of your role specifically in your company.  \n   - some other questions on bigdata, which I don't remember right now 😁  \n"
  },
  {
    "path": "DATFreightAnalytics/README.md",
    "content": "## Interview Process for Machine Learning Engineer (Personal Experience)  \n1. Resume Screening.\n2. Technical Assessment (Take Home Assignment).\n   - Questions are mostly around MLOps concepts, Machine Learning Engineering and Designing systems.\n3. Technical Round as a followup and questions.\n4. Hiring Manager Round.\n5. Leadership interview round.\n6. Final - HR Interview covering cultural and behavioral aspects.\n"
  },
  {
    "path": "Facebook/ImplementSTRSTR.py",
    "content": "{\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        s,p =input().strip().split()\n        print(strstr(s,p))\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n'''\n\tYour task is to return the index of the pattern\n\tpresent in the given string.\n\t\n\tFunction Arguments: s (given text), p(given pattern)\n\tReturn Type: Integer.\n\t\n'''\ndef strstr(s,p):\n    #code here\n    import re\n    loc = re.search(p,s)\n    if loc is not None:\n        return (loc.start())\n    else:\n        return -1"
  },
  {
    "path": "FactSet/convertArrayToWave.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n    \n    T=int(input())\n    \n    while(T>0):\n        \n        \n        N=int(input())\n        \n        A=[int(x) for x in input().split()]\n        convertToWave(A,N)\n        for i in A:\n            print(i,end=\" \")\n        \n        \n        print()\n        \n       \n        T-=1\nif __name__==\"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef convertToWave(A,N):\n    #Your code here\n    temp=0\n    for i in range(N-1):\n        if i%2 == 0:\n            if A[i] < A[i+1]:\n                temp=A[i]\n                A[i]=A[i+1]\n                A[i+1]=temp\n            else:\n                continue\n        else:\n            if A[i] > A[i+1]:\n                temp=A[i]\n                A[i]=A[i+1]\n                A[i+1]=temp\n            else:\n                continue"
  },
  {
    "path": "Flipkart/addTwoNumbers_LinkedListRep.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n# prints the elements of linked list starting with head\ndef printList(head):\n    if head is None:\n        print(' ')\n        return\n    curr_node = head\n    while curr_node:\n        print(curr_node.data,end=\" \")\n        curr_node=curr_node.next\n    print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n_a = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_a = nodes_a[::-1] # reverse the input array\n        for x in nodes_a:\n            a.append(x)  # add to the end of the list\n        n_b =int(input())\n        b = LinkedList()  # create a new linked list 'b'.\n        nodes_b = list(map(int, input().strip().split()))\n        nodes_b = nodes_b[::-1]  # reverse the input array\n        for x in nodes_b:\n            b.append(x)  # add to the end of the list\n        result_head = addBoth(a.head,b.head)\n        printList(result_head)\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to add two numbers represented \n\tin the form of the linked list.\n\t\n\tFunction Arguments: head_a and head_b (heads of both the linked lists)\n\tReturn Type: head of the resultant linked list.\n    \n    __>IMP : numbers are represented in reverse in the linked list.\n    Ex:\n        145 is represented as  5->4->1.\n    \n    resultant head is expected in the same format.\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n'''\ndef addBoth(head_a,head_b):\n    #code here\n    result = LinkedList()\n    num1 = \"\"\n    curr_node = head_a\n    while curr_node != None:\n        num1 += str(curr_node.data)\n        curr_node = curr_node.next\n    num1 = num1[::-1]\n    num2 = \"\"\n    curr_node = head_b\n    while curr_node != None:\n        num2 += str(curr_node.data)\n        curr_node = curr_node.next\n    num2 = num2[::-1]\n    num = int(num1) + int(num2)\n    num = str(num)[::-1]\n    for i in num:\n        result.append(i)\n    return result.head"
  },
  {
    "path": "Flipkart/countOfInversionsArray.py",
    "content": "# GeeksForGeeks Code - Copied#\n{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for tt in range(t):\n        n = int(input())\n        a = list(map(int, input().strip().split()))\n        print(Inversion_Count(a,n))\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to return total number of inversions\n\tpresent in the array.\n\t\n\tFunction Arguments: array a and size n\n\tReturn Type: Integer \n'''\ndef Inversion_Count(arr,n):\n    if a == sorted(a):\n        return 0\n    temp_arr = [0]*n\n    return mergesort(arr,temp_arr,0,n-1)\n    \ndef mergesort(arr,temp_arr,left,right):\n    inv_count = 0\n    if left < right:\n        mid = (left + right)//2\n        inv_count = mergesort(arr,temp_arr,left,mid)\n        inv_count += mergesort(arr,temp_arr,mid+1,right)\n        inv_count += merge(arr,temp_arr,left,mid,right)\n    return inv_count\n    \ndef merge(arr,temp_arr,left, mid, right): \n    # Merge the temp arrays back into arr[l..r] \n    i = left     # Initial index of first subarray \n    j = mid+1     # Initial index of second subarray \n    k = left     # Initial index of merged subarray \n    invcount = 0\n    while i <= mid and j <= right: \n        if arr[i] <= arr[j]:\n            temp_arr[k] = arr[i] \n            i += 1\n        else: \n            temp_arr[k] = arr[j]\n            invcount += (mid - i + 1)\n            j += 1\n        k += 1\n    # Copy the remaining elements of L[], if there \n    # are any \n    while i <= mid: \n        temp_arr[k] = arr[i] \n        i += 1\n        k += 1\n    # Copy the remaining elements of R[], if there \n    # are any \n    while j <= right: \n        temp_arr[k] = arr[j] \n        j += 1\n        k += 1\n        \n    for lr in range(left, right + 1): \n        arr[lr] = temp_arr[lr] \n    return invcount\n"
  },
  {
    "path": "Flipkart/parenthesisChecker.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n#Contributed by : Nagendra Jha\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    test_cases = int(input())\n    for cases in range(test_cases) :\n        #n = int(input())\n        #n,k = map(int,imput().strip().split())\n        #a = list(map(int,input().strip().split()))\n        s = str(input())\n        if ispar(s):\n            print(\"balanced\")\n        else:\n            print(\"not balanced\")\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\nFunction Arguments :\n\t\t@param  : s (given string containing parenthesis) \n\t\t@return : boolean True or False\n'''\n\ndef isMatchingPair(c1,c2):\n    if (c1=='(') & (c2==')'):\n        return True\n    elif (c1=='{') & (c2=='}'):\n        return True\n    elif (c1=='[') & (c2==']'):\n        return True\n    else:\n        return False\n        \ndef ispar(s):\n    # code here\n    import queue\n    stack = queue.LifoQueue()\n    \n    for i in range(len(s)):\n        if ((s[i] == '{') | (s[i] == '[') | (s[i] == '(')):\n            stack.put(s[i])\n        if ((s[i] == '}') | (s[i] == ']') | (s[i] == ')')):\n            if stack.empty():\n                return False\n            elif not isMatchingPair(stack.get(),s[i]):\n                return False\n        \n    if stack.empty():\n        return True\n    else:\n        return False"
  },
  {
    "path": "Fractal_Analytics/Arrays.md",
    "content": "Given an array A of size N as an input, return the following:  \n  + for every element of array, find the sum of elements upto that element(inclusive):  \n  \nExamples:  \n```\nA = [3,5,6,9,10], N = 5\nfor 3, sum of elements upto 3 is 0 + 1 + 2 + 3 = 6.  \nfor 5, sum of elements upto 5 is 0 + 1 + 2 + 3 + 4 + 5 = 15.  \nfor 6, sum of elements upto 6 is 0 + 1 + 2 + 3 + 4 + 5 + 6 = 21.  \nfor 9, sum of elements upto 9 is 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45.  \nfor 10, sum of elements upto 10 is 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.  \n"
  },
  {
    "path": "Fractal_Analytics/Comparator.md",
    "content": "1. Write a comparator class with overloaded methods that perform below operations  \n   - a. `compare(int a,int b)` that takes two integers `a` and `b` and returns `True` if `a == b` else `False`.  \n   - b. `compare(string a,string b)` that takes two strings `a` and `b` as parameters and returns `True` if `a == b` else `False`.  \n   - c. `compare(int a[],int b[])` that takes two 1-Dimensional Arrays `a` and `b` as parameters and checks the following\n   conditions  \n        - if length of `a` is equal to `b`.  \n        - for every index `i` of a, `a[i] == b[i]`.  \n   returns `True` only if above two conditions hold true otherwise returns `False`.  \n"
  },
  {
    "path": "Fractal_Analytics/README.md",
    "content": "# Interview Process for Analytics Consultant - 2019:  \n### First round:  \n+ Hackerrank Test (Python + SQL) or (R + SQL) test (4 python/R + 4 sql questions)(python questions are normal coding questions).  \n### Second round:  \n+ Questions on projects from CV/Machine learning algorithms for time series,classification usecases and case study(How would you approach the problem of maximizing a variable from model results)?  \n\n# Interview Process for Analytics Consultant - 2020:  \n### First round:  \n+ DoSelect Test (Python + SQL) or (R + SQL) test (4 python/R + 4 sql questions) (Python questions are not coding questions but\nquestions on pandas and numpy coding).  \n  \n# Interview Process for Senior Big Data Engineer - 2021:  \n### First round:  \n+ DoSelect Test (Coding Test).  \n  \n### Second round:  \n+ Technical questions on Hive, Spark (Accumulator and Broadcast variables usecases), real world examples, and testing coding skills - Data structures and algorithms (Time complexity and Space complexity analysis).  \n+ Focus on Spark application performance tuning techniques.  \n+ In-depth SQL questions - solve using either SQL query or dataframes/datasets API in spark.  \n\n### Third round:  \n+ Interview with the Director/VP on background, questions to check if you are the right fit for the role, etc.  \n\n### Fourth round:  \n+ HR round - process improvements, challenges faced in the past etc.  \n"
  },
  {
    "path": "Fractal_Analytics/countChampNumbers.py",
    "content": "\"\"\"\nfind the count of champ numbers in given range [X,Y] (inclusive)\nChamp numbers are numbers which have all the digits as unique\nand no digit should be greater than 5\n\n\"\"\"\n\ndef countChampNumbers(X,Y):\n    count = 0\n    for i in range(X,Y+1):\n        if len(str(i)) == 1 and i <= 5:\n            print (i)\n            count += 1\n        else:\n            if len(set(str(i))) == len(str(i)):\n                if not (('6' in str(i)) or ('7' in str(i)) or \n                        ('8' in str(i)) or ('9' in str(i))):\n                    print(i)\n                    count += 1\n    return count\n    \nif __name__ == '__main__':\n    T = int(input())\n    for tc in range(T):\n        X,Y = list(map(int, input().strip().split()))\n        print (countChampNumbers(X,Y))"
  },
  {
    "path": "Fractal_Analytics/countOfAnagrams.py",
    "content": "\"\"\"\nGiven a text and a word, find the count of occurrences of anagrams\nof word in given text\n\n\"\"\"\n\ndef countAnagrams(text,word):\n    count=0\n    b = text\n    a = word\n    for i in range(len(b)-len(a)+1):\n        if(sorted(a)==sorted(b[i:i+len(a)])):\n            count=count+1\n    return count \n\n\nif __name__ == '__main__':\n    text = str(input())\n    word = str(input())\n    print (countAnagrams(text, word))"
  },
  {
    "path": "Fractal_Analytics/numberOfGroups.py",
    "content": "\"\"\"\nA pole of the magnet is represented as \"01\" or \"10\"\n1 = North pole and 0 = South pole\nwe know the like poles of magnet repel each other but unlike poles\nattract.\nSuppose a magnet has pole \"10\" and adjacent magnet also has \"10\" \nthey attract \nif a magnet \"01\" is located adjacent to magnet \"10\" they repel.\n\nGiven a list of poles of different magnets, find the number of the\nseparate groups that magnets form into\n\nexample:\n    number of magnets = 3\n    01\n    01\n    10\n    \n    number of groups = 2 because first 2 magnets attract each other\n    so will be in the same group where as the third one repels\n    second one so will be in different group\n\"\"\"\n\n\ndef numGroups(poles):\n    groups = [poles[0]]\n    for i in range(1,len(poles)):\n        if poles[i][0] == groups[-1][0]:\n            groups.append(poles[i])\n        else:\n            groups.append(' ')\n            groups.append(poles[i])\n    concat_groups = ''.join(groups)\n    print (concat_groups)\n    return len(concat_groups.split(' '))\n    \nif __name__ == '__main__':\n    n = int(input())\n    poles = []\n    for tc in range(n):\n        pole = input()\n        poles.append(pole)\n    print (numGroups(poles))"
  },
  {
    "path": "Fractal_Analytics/sorting_words.md",
    "content": "Given a sentence, sort the words of a sentence according to the their individual lengths. If one or more words have same length\nthen sort the words by first character of the word.\n\n```\nExample: \nInput: The quick brown fox jumps over the lazy dog\nOutput: dog fox the The lazy over brown jumps quick\n\n```\n+ This problem can be extended to sorting the words by second letter in case of collision with first letter and continue\ntill the end of word and stop when collision is resolved.  \n"
  },
  {
    "path": "Fractal_Analytics/substrings.md",
    "content": "\n2. Get the number of distinct substrings possible for a given string, you can use the below operations:  \n  \n   - a. Remove 0 or more characters from left side of the string.  \n   - b. Remove 0 or more characters from right side of string.  \n   - c. Remove 0 or more characters from both left and right side of string.  \n     \nExamples:  \n```\nInput  : str = “ababa”\nOutput : 10\nTotal number of distinct substring are 10, which are,\n\"\", \"a\", \"b\", \"ab\", \"ba\", \"aba\", \"bab\", \"abab\", \"baba\"\nand \"ababa\"\n```  \n```\nInput : abcd\nOutput : abcd abc ab a bcd bc b cd c d\nAll Elements are Distinct\n```  \n```\nInput : aaa\nOutput : aaa aa a aa a a\nAll elements are not Distinct\n```  \n"
  },
  {
    "path": "Fre8wise/README.md",
    "content": "# Process for Software engineer role:  \n## First round:  \n1. First round is with founder of the company - This is an exploratory call about company's profile, your background, projects and why you are looking for a change, CTC details - Even a demo of what company is doing is included on Zoom call  \n\n## Second round:  \n1. Technical interview with one of the technical leads.  \n2. Questions from the CV, work experience, challenges in projects you have undertaken.  \n3. Design a queueing system that serves multiple agents looking for differnet datasets being produced from different producers/systems.  \n4. Memory management in Data engineering pipelines.  \n5. Questions on lambda architecture.  \n6. Questions on nitty-gritty details of how you executed projects in production.  \n7. Focus on system design and understanding.  \n"
  },
  {
    "path": "Fre8wise/manipulate_string.py",
    "content": "\"\"\"\nSolve the following algorithm problem:\n    Given a string, develop a solution that removes only 1's\n    in the beginning\n    \n    Examples:\n        1198fgh098nm -> 98fgh098nm\n        a1198fgh098nm -> a1198fgh098nm\n        a1198fgh098nm11 -> a1198fgh098nm11\n\"\"\"\n\ns = \"1198fgh098nm\"\n\n\ndef changeString(s):\n    try:\n        while (s.index(\"1\") == 0):\n            slist = list(s)\n            temp = slist.pop(0)\n            s = \"\".join(slist)\n    except:\n        pass\n    return s\n\nif __name__ == '__main__':\n    s = input()\n    print (changeString(s))"
  },
  {
    "path": "Goldman-Sachs/convertArrayToWave.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n    \n    T=int(input())\n    \n    while(T>0):\n        \n        \n        N=int(input())\n        \n        A=[int(x) for x in input().split()]\n        convertToWave(A,N)\n        for i in A:\n            print(i,end=\" \")\n        \n        \n        print()\n        \n       \n        T-=1\nif __name__==\"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef convertToWave(A,N):\n    #Your code here\n    temp=0\n    for i in range(N-1):\n        if i%2 == 0:\n            if A[i] < A[i+1]:\n                temp=A[i]\n                A[i]=A[i+1]\n                A[i+1]=temp\n            else:\n                continue\n        else:\n            if A[i] > A[i+1]:\n                temp=A[i]\n                A[i]=A[i+1]\n                A[i+1]=temp\n            else:\n                continue"
  },
  {
    "path": "Goldman-Sachs/numberOfSquares_in_NbyN_CheesBoard.py",
    "content": "def num_of_squares(n):\n    if n == 1:\n        return (1)\n    else:\n        nSquares = 0\n        for I in range(1,n+1):\n            nSquares = nSquares + (I*I)\n        return (nSquares)\n            \n\nif __name__ == '__main__':\n    T = int(input())\n    for tcase in range(T):\n        n = int(input())\n        print (num_of_squares(n))"
  },
  {
    "path": "Goldman-Sachs/printNumbersContain123.py",
    "content": "def contains123(arr):\n    c = {'1','2','3'}\n    tracker = []\n    arr = sorted(arr)\n    for i in arr:\n        a = set(str(i))\n        if a.issubset(c):\n            print (i,end=\" \")\n            tracker.append(1)\n        else:\n            tracker.append(0)\n    if len(set(tracker))==1 and 0 in tracker:\n        print (-1,end=\"\")\n\nif __name__ == '__main__':\n    t = int(input())\n    for tcase in range(t):\n        n = int(input())\n        arr = list(map(int,input().strip().split()))\n        contains123(arr)\n        print ('\\n',end=\"\")"
  },
  {
    "path": "Goldman-Sachs/repeatingCharacter_LeftmostOccurrence.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for i in range(t):\n        s=str(input())\n        index=repeatingCharacter(s)\n        if(index==-1):\n            print(-1)\n        else:\n            print(s[index])\n            \n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to return the lefmost index of the repeating \n\tcharacter whose first appereance is left most or return\n\t-1 if all characters are distinct.\n\t\n\tFunction Arguments: s (given string)\n\tReturn Type: integer\n'''\ndef repeatingCharacter(s):\n    #code here\n    import collections\n    freqs = collections.Counter(s)\n    if len(set(freqs.values())) == 1 and 1 in set(freqs.values()):\n        return -1\n    else:\n        inds = []\n        for k,v in freqs.items():\n            if v > 1:\n                inds.append(s.index(k))\n        return min(inds)"
  },
  {
    "path": "Google/First_Recurring_Character_In_String.py",
    "content": "from collections import Counter\ninput_string = input()\n\ndef firstRecurringChar(input_string):\n    recurring_chars= []\n    count_dict = Counter(input_string)\n    for x, y in count_dict.items():\n        if y > 1:\n            recurring_chars.append(x)\n    if recurring_chars:\n        return recurring_chars[0]\n    else:\n        return (-1)\n    \nif __name__ == '__main__':\n    print (firstRecurringChar(input_string))"
  },
  {
    "path": "Google/allocateMinimumPages.py",
    "content": "import math\ndef isValid(arr,n,k,mi):\n    std = 1\n    curr = 0\n    for i in range(n):\n        if curr + arr[i] > mi:\n            curr = arr[i]\n            std += 1\n            if std > k:\n                return False\n        else:\n            curr += arr[i]\n    return True\n\ndef allocMinPages(arr,n,k):\n    if k > n:\n        return -1\n    s,totalpage = 0,0\n    for i in range(n):\n        totalpage += arr[i]\n        s = max(s,arr[i])\n    e = totalpage\n    finalAns = s\n    while s <= e:\n        mid = math.floor((s+e)/2)\n        if isValid(arr,n,k,mid):\n            finalAns = mid\n            e = mid - 1\n        else:\n            s = mid + 1\n    return finalAns\n    \nif __name__ == '__main__':\n    T = int(input())\n    for tcase in range(T):\n        N = int(input())\n        arr = list(map(int,input().strip().split()))\n        M = int(input())\n        print (allocMinPages(arr,N,M))"
  },
  {
    "path": "Google/checkPairsWithGivenSum.py",
    "content": "\"\"\"\nThis problem was recently asked by Google.\n\nGiven a list of numbers and a number k, return whether any two numbers from the \nlist add up to k.\n\nFor example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.\n\"\"\"\n\n\ndef isPairWithGivenSum(arr,n,x):\n    left,right = 0,n-1\n    arr = sorted(arr)\n    while left < right:\n        if ((arr[left] + arr[right]) < x):\n            left += 1\n        elif (arr[left] + arr[right] == x):\n            return True\n        elif (arr[left] + arr[right] > x):\n            right -= 1\n    return False\n\nif __name__ == '__main__':\n    T = int(input())\n    for tcs in range(T):\n        arr = list(map(int,input().strip().split()))\n        n = len(arr)\n        x = int(input())\n        print (isPairWithGivenSum(arr,n,x))"
  },
  {
    "path": "Google/maxIndexDiffOfArray.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            n=int(input())\n            \n            arr=[int(x) for x in input().strip().split()]\n            print(maxIndexDiff(arr,n))\n            \n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef maxIndexDiff(arr, n): \n    ##Your code here\n    maxxDiff = 0\n    for i in range(n):\n        for j in range(i+1,n):\n            if arr[i]<=arr[j]:\n                if maxxDiff < j - i:\n                    maxxDiff = j - i\n    return maxxDiff"
  },
  {
    "path": "Grofers/QuickSort.py",
    "content": "{\n#Initial Template for Python 3\nif __name__ == \"__main__\":\n    t=int(input())\n    for i in range(t):\n        n=int(input())\n        arr=list(map(int,input().split()))\n        quickSort(arr,0,n-1)\n        for i in range(n):\n            print(arr[i],end=\" \")\n        print()\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\ndef quickSort(arr,low,high):\n    if low < high:\n \n        # pi is partitioning index, arr[p] is now\n        # at right place\n        pi = partition(arr,low,high)\n \n        # Separately sort elements before\n        # partition and after partition\n        quickSort(arr, low, pi-1)\n        quickSort(arr, pi+1, high)\n        \ndef partition(arr,low,high):\n    #add code here\n    tmp = 0\n    pivot = arr[high]\n    i = low - 1\n    for j in range(low,high):\n        if arr[j] <= pivot:\n            i += 1\n            tmp = arr[i]\n            arr[i] = arr[j]\n            arr[j] = tmp\n    tmp = arr[i+1]\n    arr[i+1] = arr[high]\n    arr[high] = tmp\n    return i+1"
  },
  {
    "path": "Guardant-Health/README.md",
    "content": "# Hackerrank Test (Personal Experience)  \n"
  },
  {
    "path": "Guardant-Health/fallen_leaves.py",
    "content": "\"\"\"\nCoding Test - Hackerrank\n\nGiven an array that has number of leaves on N trees (size of array = N)(arr[i]\nrepresents number of leaves for ith tree),\npercentage, array of days (can be in any order), starting and ending arrays\n\nScenario:\n    every day from each tree, given percentage of leaves will be fallen.\n    \n    Task:\n        There are q queries,each query has day[q].starting[q] and ending[q]\n        find out for each query how many leaves are fallen in total from\n        all the trees with given start and end indices.\n        \n    Example:\n        arr = [10,20,30,20,10]\n        percentage = 30\n        days = [1,1,2]\n        starting = [2,1,1]\n        ending = [4,3,4]\n        \n        after first day number of fallen leaves in the given range of starting[0]\n        and ending[0] is 6 + 9 + 6 = 21 (required answer)\n        Remaining leaves after first day = [7,14,21,14,7]\n        \nIn this way answer all the queries\n\n\"\"\""
  },
  {
    "path": "Guardant-Health/maintainMinimumStartingNumber.py",
    "content": "\"\"\"\nCoding Test - Hackerrank\n\nwhat is the minimum starting number to maintain such that the running sum will\nalways be atleast 1\n\nExample: \n    arr = [3,-6,5,-2,1]\n    4 is the mininum number we need to start with\n    Let's check:\n        4 + 3 = 7\n        7 + (-6) = 1\n        1 + 5 = 6\n        6 + (-2) = 4\n        4 + 1 = 5\n        so it's 4.\n        \n    arr = [-4,3,-2,1]\n    5 is the minimum number we need to start with\n    Let's check:\n        5 + (-4) = 1\n        1 + 3 = 4\n        4 + (-2) = 2\n        2 + 1  3\n        so it's 5 \n\"\"\"\n\ndef minStartNumber(arr):\n    bounds = []\n    total = 1\n    for el in arr:\n        total += (-1 * el)\n        bounds.append(total)\n    return max(bounds)\n\n\nif __name__ == '__main__':\n    arr1 = [3,-6,5,-2,1]\n    print (minStartNumber(arr1))\n    \n    arr2 = [-4,3,-2,1]\n    print (minStartNumber(arr2))"
  },
  {
    "path": "HighRadius-Technologies/README.md",
    "content": "## Interview questions (Personal Experience):  \n\n#### 1. Confusion matrix for any classification algorithm is showed and what are precision and recall values from the matrix?  \n  \n+ **What is precision**: `Number of True Positives / (Total number of Total Positives and False Positives)`  \n+ **What is Recall** : `Number of True Positives / (Total Number of Total Positives and False Negatives)`  \n\n#### 2. How do you deal with overfitting in your machine learning model?  \n  \n+ Regularization - (LASSO or Ridge Regression) (L1 and L2 regularization).  \n+ K-Fold cross validation with variable K.  \n+ Resampling of Train and Test splits of a datasets, sometimes involve out-of-time validation dataset.  \n+ Dimensionality Reduction in case of many features in a dataset.  \n+ Ensemble Learning.  \n\n#### 3. How do you explain p-value to a layman? - Hypothesis testing.  \n\n+ p-value is metric by which we decide statistically significant variables.  \n+ It's a measure of how extreme an observed value is under the assumed null hypothesis: the smaller it is, the more extreme the \nobservation. We can define p-value as the smallest significance level at which the null hypothesis would be rejected.  \n+ As the p-value gets smaller, we start wondering if the null hypothesis really is true and well maybe we should change our minds \n(and reject the null hypothesis).  \n\n#### 4. How do you deal with concurrent predictions from decision Trees in ensemble algorithms like random forest?\n+ Do some google research on this, there are multiple techniques to deal with this.\n"
  },
  {
    "path": "Hike/QuickSort.py",
    "content": "{\n#Initial Template for Python 3\nif __name__ == \"__main__\":\n    t=int(input())\n    for i in range(t):\n        n=int(input())\n        arr=list(map(int,input().split()))\n        quickSort(arr,0,n-1)\n        for i in range(n):\n            print(arr[i],end=\" \")\n        print()\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\ndef quickSort(arr,low,high):\n    if low < high:\n \n        # pi is partitioning index, arr[p] is now\n        # at right place\n        pi = partition(arr,low,high)\n \n        # Separately sort elements before\n        # partition and after partition\n        quickSort(arr, low, pi-1)\n        quickSort(arr, pi+1, high)\n        \ndef partition(arr,low,high):\n    #add code here\n    tmp = 0\n    pivot = arr[high]\n    i = low - 1\n    for j in range(low,high):\n        if arr[j] <= pivot:\n            i += 1\n            tmp = arr[i]\n            arr[i] = arr[j]\n            arr[j] = tmp\n    tmp = arr[i+1]\n    arr[i+1] = arr[high]\n    arr[high] = tmp\n    return i+1"
  },
  {
    "path": "IQLECT/LargestPrimeFromSubsetSum.py",
    "content": "# Q)Find largest possible prime number that can be generated by adding all the elements of any subset of the given array. \n# Return -1 if it is impposible.\n# Implement the method largestPrime() below\n\n# \t------------------------------\n# \tConstraints:\n# \tLength of array < 16\n# \tEach element in array is zero or a positive integer < 10000\n# \t------------------------------\n\n# \tExample\n# \t\tInput:\n# \t\t[3, 3, 2, 2]\n\n# \t\tOutput:\n# \t\t7\n\n\n# \t\tInput:\n# \t\t[0, 2, 4, 1, 2, 4, 4]\n\n# \t\tOutput:\n# \t\t17\n\n\n# \t\tInput:\n# \t\t[6]\n\n# \t\tOutput:\n# \t\t-1\n\n\n\n\n\n# Implement this method to return the expected output\n\nimport itertools\n\ndef largestPrime(a):\n    allPrimes = []\n    for i in range(1,len(a)+1):\n        allCombs = list(itertools.combinations(a,i))\n        for j in allCombs:\n            req_num = sum(j)\n            if req_num == 2 | req_num == 3:\n                allPrimes.append(req_num)\n            isPrime = []\n            if (req_num > 1) & (req_num != 2) & (req_num != 3): \n               for i in range(2, req_num//2):\n                   if (req_num % i) == 0:\n                       isPrime.append(0)\n                       break \n                   else:\n                       isPrime.append(1)\n            else:\n                isPrime.append(0)\n            if 1 in isPrime and 0 not in isPrime:\n                allPrimes.append(req_num)\n    if allPrimes:\n        return max(allPrimes)\n    else:\n        return -1\n    \n# No need to change below this\n# No need to change below this\n# No need to change below this\n# No need to change below this\n# No need to change below this\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n#################################################################################################################\n# No need to change below this\nimport traceback\ndef testLargestPrime():\n\tdata = [\n\t\t[3, 3, 2, 2],\n\t\t[0, 2, 4, 1, 2, 4, 4],\n\t\t[6],\n\t\t[87, 47, 33],\n\t\t[772, 312, 421, 706, 258, 583],\n\t\t[854, 964, 59, 747, 753, 511, 40, 340, 703],\n\t\t[2, 9],\n\t\t[7, 6, 5, 2, 2, 5, 0, 0],\n\t\t[36, 81, 37, 89, 36, 77, 89, 33, 36, 45],\n\t\t[0,3,49]\n\n\t]\n\t\n\toutput = [7, 17, -1, 167, 1697, 4931, 11, 23, 523, 3]\n\n\taccepted = 0\n\tfor i in range(len(data)):\n\t\ttry:\t\t\t\n\t\t\tprint (\"Test case: \" + str(i))\n\t\t\tprint (\"Input:\")\n\t\t\tprint (str(data[i]))\n\t\t\tprint (\"Expected output:\")\n\t\t\tprint (output[i])\n\t\t\tprint (\"Actual Output:\")\t\t\t\n\t\t\tans = largestPrime(data[i])\n\t\t\tprint (ans)\n\t\t\tif(ans == output[i]):\n\t\t\t\taccepted +=1\n\t\texcept:\n\t\t\tprint(traceback.format_exc())\n\n\t\tprint (\"\\n\\n\")\n\n\tprint (\"Verdict:\")\n\tif(accepted == len(output)):\n\t\tprint (\"------All test passed-------\")\n\telse:\n\t\tprint (\"-----Test Failed: \" + str(accepted) + \" tests passed out of \" + str(len(output)) + \"-----\")\t\n\n\ntestLargestPrime()"
  },
  {
    "path": "IQLECT/README.md",
    "content": "# Asked to solve these questions in-person (In office) (No platform)\n"
  },
  {
    "path": "InMobi/README.md",
    "content": "# Interview Process for Big Data Engineer 2020 (Personal):  \n1. First round of interview with onshore engineering manager from U.S.A.  \n2. Questions about your work experience on distributed systems, spark and data engineering pipelines.  \n3. what is it that you do as a part of your daily routine at work?  \n4. Tell me your understanding about hadoop?  \n5. What kind of challenges did you face in your projects? and How did you resolve them?  \n6. How do you handle memory leaks/failure of jobs due to memory errors?  \n7. Explain your understanding of hive internal table vs external table?  \n8. How did you optimize complex queries in hive?  - partitions, buckets etc  \n9. How do you handle spark applications that are taking too long (certain task is leading to memory leaks)?  \n"
  },
  {
    "path": "Infrrd/problem01/maximumRowsWithAll1s.py",
    "content": "import collections\n\ndef maximumRows(binary_matrix,K):\n    N = len(binary_matrix)\n    M = len(binary_matrix[0])\n    numOf1s = [collections.Counter(x)[1] for x in binary_matrix]\n    #Number of flips <= K\n    maximum1s = max(numOf1s)\n    #numOfRows_Maximum1s = collections.Counter(numOf1s)[maximum1s]\n    total = []\n    for i in range(len(binary_matrix)):\n        xyPairs1 = []\n        for j in range(M):\n            if binary_matrix[i][j] == 1:\n                xyPairs1.append(j)\n        total.append(xyPairs1)\n    maximum1sRows = [k for k,v in enumerate(numOf1s) if v == maximum1s]\n    #maxmimize first Row\n    finalCountList = []\n    for e in maximum1sRows:\n        row = set(total[e])\n        UniversalSet = set(range(M))\n        needInc = UniversalSet-row\n        checkList = sorted(list(set(range(N)) - {e}))\n        a = checkList[0]\n        b = checkList[len(checkList)-1]\n        countList = []\n        for u in total[a:b+1]:\n            count = 0\n            if needInc & set(u):\n                count += len(needInc & set(u))\n            countList.append(count)\n        finalCountList.append(countList)\n    return (len(finalCountList)//K)\n        \n        \nif __name__ == '__main__':\n    N,M,K = list(map(int,input().strip().split()))\n    binary_matrix = []\n    for I in range(N):\n        row = list(map(int,input().strip().split()))\n        binary_matrix.append(row)\n    print (maximumRows(binary_matrix,K))"
  },
  {
    "path": "Infrrd/problem02/countMe.py",
    "content": "def countMe(arrA,arrL,arrR,arrX):\n    resultCount = []\n    for b in range(len(arrX)):\n        targetX = arrX[b]\n        p = arrL[b]\n        q = arrR[b]\n        resultCount.append(countOfNums(arrA[p-1:q],targetX))\n    return (\" \".join(str(i) for i in resultCount))\n\ndef countOfNums(array,target):\n    C = 0\n    for x in array:\n        if target%x == 0:\n            C += 1\n    return (C)\n\nif __name__ == '__main__':\n    sizeOfA = int(input())\n    arrA = list(map(int,input().strip().split()))\n    numQ = int(input())\n    arrL = list(map(int,input().strip().split()))\n    arrR = list(map(int,input().strip().split()))\n    arrX = list(map(int,input().strip().split()))\n    print (countMe(arrA,arrL,arrR,arrX))\n    "
  },
  {
    "path": "Instabase/Add2BinaryStrings.py",
    "content": "\"\"\"\nAdd two binary strings and get the resultant\nHint:\n    Try it without converting individual entities into numerical equivalents\n    \nSolution:\n    Refer: https://www.geeksforgeeks.org/program-to-add-two-binary-strings/\n\"\"\""
  },
  {
    "path": "Instabase/README.md",
    "content": "# Coding questions on Enthire (Personal Experience)\n"
  },
  {
    "path": "Instabase/checkPairsWithGivenSum.py",
    "content": "\"\"\"\nDaily Coding Problem #1\nThis problem was recently asked by Google.\n\nGiven a list of numbers and a number k, return whether any two numbers from the \nlist add up to k.\n\nFor example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.\n\"\"\"\n\n\ndef isPairWithGivenSum(arr,n,x):\n    left,right = 0,n-1\n    arr = sorted(arr)\n    while left < right:\n        if ((arr[left] + arr[right]) < x):\n            left += 1\n        elif (arr[left] + arr[right] == x):\n            return True\n        elif (arr[left] + arr[right] > x):\n            right -= 1\n    return False\n\nif __name__ == '__main__':\n    T = int(input())\n    for tcs in range(T):\n        arr = list(map(int,input().strip().split()))\n        n = len(arr)\n        x = int(input())\n        print (isPairWithGivenSum(arr,n,x))"
  },
  {
    "path": "Intuit/BuySellStock.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            n=int(input())\n            \n            arr=[int(x) for x in input().strip().split()]\n            stockBuySell(arr,n)\n            print()\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef stockBuySell(A,n):\n    if A == sorted(A):\n        print (\"(\" + str(0) + \" \" + str(n-1) + \")\",end=\" \")\n    elif A == sorted(A,reverse=True):\n        print (\"No Profit\",end = \" \")\n    else:\n        local_min = []\n        local_max = []\n        for i,v in enumerate(A):\n            if i == 0:\n                if v < A[i+1]:\n                    local_min.append(i)\n            elif i == n-1:\n                if v > A[i-1]:\n                    local_max.append(i)\n            else:\n                if A[i-1] <= v and v >= A[i+1]:\n                    local_max.append(i)\n                if A[i-1] >= v and v <= A[i+1]:\n                    local_min.append(i)\n        if len(local_max) == len(local_min):\n            for i in range(len(local_max)):\n                x = \" \".join([str(local_min[i]),str(local_max[i])])\n                print (\"(\"+x+\")\",end=\" \")\n        else:\n            x = \" \".join([str(max(local_min)),str(max(local_max))])\n            print (\"(\"+x+\")\",end = \" \")"
  },
  {
    "path": "Intuit/binaryArraySort.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            N=int(input())\n            A=list(map(int,input().split()))\n            \n            binSort(A,N)\n            \n            for i in A:\n                print(i,end=\" \")\n            print()\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n##Complete this function\ndef binSort(arr, n): \n    #Your code here\n    \n    \n    '''\n    No need to print the array\n    '''\n    c0 = arr.count(0)\n    c1 = arr.count(1)\n    for i in range(c0):\n        arr[i] = 0\n    for i in range(c0,c0+c1):\n        arr[i] = 1"
  },
  {
    "path": "Kritikal-Solutions/Delete_Without_Head_Pointer.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    def getNode(self,value): # return node with given value, if not present return None\n        curr_node=self.head\n        while(curr_node.next and curr_node.data != value):\n            curr_node=curr_node.next\n        if(curr_node.data==value):\n            return curr_node\n        else:\n            return None\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes = list(map(int, input().strip().split()))\n        for x in nodes:\n            a.append(x)\n        del_elem = int(input())\n        to_delete=a.getNode(del_elem)\n        deleteNode(to_delete)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n    Your task is to delete the given node from\n\tthe linked list, without using head pointer.\n\t\n\tFunction Arguments: node (given node to be deleted) \n\tReturn Type: None, just delete the given node from the linked list.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n\tContributed By: Nagendra Jha\n'''\ndef deleteNode(curr_node):\n    #code here\n    prev = None\n    curr = a.head\n    while curr != None and curr_node != None:\n        if curr.data == curr_node.data:\n            if prev:\n                prev.next = curr.next\n            else:\n                a.head = curr.next\n            return\n        prev = curr\n        curr = curr.next"
  },
  {
    "path": "LeadSquared/README.md",
    "content": "# Coding Questions on mettl platform (Personal Experience)\n"
  },
  {
    "path": "LeadSquared/UniqueWaysToClimbStaircase.py",
    "content": "\"\"\"\nThis question is asked in Interview\n    \nThere are n stairs, a person standing at the bottom wants to reach the \ntop. The person can climb either 1 stair or 2 stairs at a time. Count \nthe number of ways, the person can reach the top.\n\nExample:\n    number of stairs = 5\n    steps allowed = 1 or 2\n\"\"\"\n\ndef countWays(n,m):\n    \"\"\"\n    Solution to above problem:\n        Pros: \n            It will consider all the possible steps from 1 to given m.\n        Cons:\n            No control by external user (if user wants to give only certain step values\n            say in the form of an array).\n    \"\"\"\n    res = [None] * (n+1)\n    temp = 0\n    res[0] = 1\n    for i in range(1,n+1):\n        s = i - m - 1\n        e = i - 1\n        if s >= 0:\n            temp -= res[s]\n        temp += res[e]\n        res[i] = temp\n        print (res)\n    return res[n]\n\nif __name__ == '__main__':\n    n,m = 5,2\n    print (countWays(n,m))\n    n,m = 5,3\n    print (countWays(5,3))\n\n\ndef countWays1(n,args):\n    \"\"\"\n    Solution that mitigates the cons of above solution\n    Give allowed step values in the form of an array (here it is args)\n    \"\"\"\n    m = len(args)\n    count = [0 for i in range(n + 1)] \n      \n    # base case \n    count[0] = 1\n      \n    # Count ways for all values up  \n    # to 'N' and store the result \n    for i in range(1, n + 1): \n        for j in range(m): \n  \n            # if i >= arr[j] then \n            # accumulate count for value 'i' as \n            # ways to form value 'i-arr[j]' \n            if (i >= args[j]): \n                count[i] += count[i - args[j]] \n      \n    # required number of ways  \n    return count[n] \n\nif __name__ == '__main__':\n    print (countWays1(5,[2,3]))\n    print (countWays1(5,[1,3,4]))\n    print (countWays1(4,[1,3,4]))\n    print (countWays1(10,[1,3,4]))\n    print (countWays1(6,[3,2]))\n    print (countWays1(5,[1,2,3]))\n    print (countWays1(4,[1]))\n    print (countWays1(4,[2]))\n    print (countWays1(6,[3]))"
  },
  {
    "path": "LeadSquared/maximumSumLikeTimeCoefficients.py",
    "content": "\"\"\"\nCoding Test - Round 1\n\nGiven an array of N integers (negative integers allowed) which say likings of\nN foods by a customer\n\nTime taken to prepare a food arr[i] is i\n\nlike-time co-efficient of food is defined as i*arr[i]. Sum of like-time\nco-efficients can be obtained by doing the add up of i*arr[i]\n\nFind the maximum sum of like-time co-efficients that can be achieved from\na given array.\n\nHint: Consider all combinations of likings from a given array.\n\nHere is the idea:\n\n\"\"\"\n\nimport itertools\n\ndef maxSumLikeTimeCoeff(arr,N):\n    all_sums = []\n    for r in range(1,N+1):\n        combinations = set(itertools.combinations(arr,r))\n        for x in combinations:\n            sums = 0\n            for i in range(len(x)):\n                sums += (i+1) * x[i]\n            all_sums.append(sums)\n    return max(all_sums)\n\nif __name__ == '__main__':\n    N = int(input())\n    arr = list(map(int,input().strip().split()))\n    print (maxSumLikeTimeCoeff(arr,N))"
  },
  {
    "path": "LeadSquared/totalDistanceByStreetLights.py",
    "content": "\"\"\"\nCoding Test - Round 1\n\nGiven N street lights, and an array of tuples which signify the start and \nend distances of street covered by that street light.\n\nFind the total distance covered by all the street lights\n\nEx:1\n    N = 1\n    arr = [(5,10)]\n    Number of street lights = 1\n    and distance covered by street light i is 5m to 10m which is 10-5 = 5m\n    \nEx:2  \n    N = 2\n    arr = [(5,10),(8,12)]\n    Number of street lights = 2\n    street light 0 = 10 - 5 = 5\n    street light 1 = 12 - 8 = 4\n    common region = 10 - 8 = 2\n    total distance = (5 + 4 - 2) = 7\n    \n\"\"\"\n\ndef total_distance(intervals):\n    if not intervals:\n        return 0\n    if len(intervals) == 1:\n        return abs(intervals[0][0] - intervals[0][1])\n    result = 0\n    common = 0\n    intervals = sorted(intervals,key=lambda x: x[0])\n    for i in range(len(intervals)):\n        result += abs(intervals[i][0] - intervals[i][1])\n    for i in range(len(intervals)-1):\n        if intervals[i][1] > intervals[i+1][0]:\n            common += abs(intervals[i][1] - intervals[i+1][0])\n    result = abs(result - common)\n    return result\n\nif __name__ == '__main__':\n    arr1 = [(5,10)]\n    print (total_distance(arr1))\n    arr2 = [(5,10),(8,12)]\n    print (total_distance(arr2))\n    \n    #subset testcase\n    arr3 = [(2,9),(3,6)]\n    print (total_distance(arr3))"
  },
  {
    "path": "MAQ_Software/Closet0s1s2s.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for i in range(t):\n        n=int(input())\n        a=list(map(int,input().strip().split()))\n        segragate012(a,n)\n        print(*a)\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n''' Your task to is sort the array a of 0s,1s and 2s\n    of size n. You dont need to return anything.'''\ndef segragate012(a,n):\n    #code here\n    c0 = a.count(0)\n    c1 = a.count(1)\n    c2 = a.count(2)\n    for i in range(c0):\n        a[i] = 0\n    for i in range(c0,c0+c1):\n        a[i] = 1\n    for i in range(c0+c1,c0+c1+c2):\n        a[i] = 2\n    #print (\" \".join(str(i) for i in a),end=\"\")"
  },
  {
    "path": "MakeMyTrip/rotateLinkedListByKelements.py",
    "content": "{\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    def push(self, new_data):\n        new_node = Node(new_data)\n        new_node.next = self.head\n        self.head = new_node\n    def printList(self):\n        temp = self.head\n        while(temp):\n            print(temp.data, end=\" \")\n            # arr.append(str(temp.data))\n            temp = temp.next\n        print(\"\")\nif __name__ == '__main__':\n    start = LinkedList()\n    t = int(input())\n    while(t > 0):\n        llist = LinkedList()\n        n = int(input())\n        values = list(map(int, input().strip().split()))\n        for i in reversed(values):\n            llist.push(i)\n        k = int(input())\n        new_head = rotateList(llist.head, k)\n        llist.head = new_head\n        llist.printList()\n        t -= 1\n# Contributed by: Harshit Sidhwa\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n# Your task is to complete this function\n'''\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n'''\n# This function should rotate list counter-\n# clockwise by k and return new head (if changed) \ndef rotateList(head, k):\n    # code here\n    global llist\n    llist = LinkedList()\n    C = 0\n    curr_node = head\n    part1 = []\n    part2 = []\n    while curr_node != None:\n        if C <= k-1:\n            part1.append(curr_node.data)\n        elif C > k-1:\n            part2.append(curr_node.data)\n        C += 1\n        curr_node = curr_node.next\n    total = reversed(part2 + part1)\n    for i in total:\n        llist.push(i)\n    return llist.head"
  },
  {
    "path": "MakeMyTrip/sortedLinkedList012s.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n# prints the elements of linked list starting with head\ndef printList(head):\n    if head is None:\n        print(' ')\n        return\n    curr_node = head\n    while curr_node:\n        print(curr_node.data,end=\" \")\n        curr_node=curr_node.next\n    print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes_a = list(map(int, input().strip().split()))\n        for x in nodes_a:\n            a.append(x)  # add to the end of the list\n        printList(segregate(a.head))\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to segregate the list of \n\t0s,1s and 2s.\n\t\n\tFunction Arguments: head of the original list.\n\tReturn Type: head of the new list formed.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n\tContributed By: Nagendra Jha\n'''\ndef segregate(head):\n    #code here\n    global a\n    a = LinkedList()\n    curr_node = head\n    mylist = []\n    while curr_node != None:\n        mylist.append(curr_node.data)\n        curr_node = curr_node.next\n    mylist = sorted(mylist)\n    for i in mylist:\n        a.append(i)\n    return a.head"
  },
  {
    "path": "Mastek/README.md",
    "content": "Consider the below employee table where ManagerID is mapped to each EmployeeID:\n\nInput:\n| EmployeeID | EmployeeName | ManagerID |\n|------------|--------------|-----------|\n|    400     |    A1        |    null   |\n|    401     |    A2        |    400    |\n|    500     |    A3        |    401    |\n|    501     |    A4        |    401    |\n|    502     |    A5        |    501    |\n\nWrite the SQL query that identifies the level of each manager as mentioned in the below output:\n\n| EmployeeID | EmployeeName | ManagerID | Level |\n|------------|--------------|-----------|-------|\n|   400      |   A1         |   null    |   0   |\n|   401      |   A2         |   400     |   1   |\n|   500      |   A3         |   401     |   2   | \n|   501      |   A4         |   401     |   2   |\n|   502      |   A5         |   501     |   3   |\n\n\n### Solution:\n               400\n                  |\n              401 (depth from 400 = 1)\n              /   \\\n          500  501 (depth from 400 = 2)\n                         \\\n                          502 (depth from 400 = 3)\n\n400 -> 401  \n401 -> 500, 501  \n501 -> 502  \n\n**What we want to do here is use RECURSIVE CTE to traverse the tree in SQL and compute the depth at every level.**\n"
  },
  {
    "path": "Mastek/computedepth.sql",
    "content": "-- Oracle solution\n\nWITH RecursiveCTE (lvl, ManagerID, EmployeeID) AS (\n   SELECT 1 AS lvl, ManagerID, EmployeeID\n   FROM employees\n   WHERE ManagerID IS NULL\n   UNION ALL\n   SELECT lvl + 1, employees.ManagerID, employees.EmployeeID\n   FROM employees\n   JOIN RecursiveCTE\n     ON employees.ManagerID = RecursiveCTE.EmployeeID\n)\nSELECT * FROM RecursiveCTE;\n"
  },
  {
    "path": "Microsoft/countOfInversionsArray.py",
    "content": "# GeeksForGeeks Code - Copied#\n{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for tt in range(t):\n        n = int(input())\n        a = list(map(int, input().strip().split()))\n        print(Inversion_Count(a,n))\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to return total number of inversions\n\tpresent in the array.\n\t\n\tFunction Arguments: array a and size n\n\tReturn Type: Integer \n'''\ndef Inversion_Count(arr,n):\n    if a == sorted(a):\n        return 0\n    temp_arr = [0]*n\n    return mergesort(arr,temp_arr,0,n-1)\n    \ndef mergesort(arr,temp_arr,left,right):\n    inv_count = 0\n    if left < right:\n        mid = (left + right)//2\n        inv_count = mergesort(arr,temp_arr,left,mid)\n        inv_count += mergesort(arr,temp_arr,mid+1,right)\n        inv_count += merge(arr,temp_arr,left,mid,right)\n    return inv_count\n    \ndef merge(arr,temp_arr,left, mid, right): \n    # Merge the temp arrays back into arr[l..r] \n    i = left     # Initial index of first subarray \n    j = mid+1     # Initial index of second subarray \n    k = left     # Initial index of merged subarray \n    invcount = 0\n    while i <= mid and j <= right: \n        if arr[i] <= arr[j]:\n            temp_arr[k] = arr[i] \n            i += 1\n        else: \n            temp_arr[k] = arr[j]\n            invcount += (mid - i + 1)\n            j += 1\n        k += 1\n    # Copy the remaining elements of L[], if there \n    # are any \n    while i <= mid: \n        temp_arr[k] = arr[i] \n        i += 1\n        k += 1\n    # Copy the remaining elements of R[], if there \n    # are any \n    while j <= right: \n        temp_arr[k] = arr[j] \n        j += 1\n        k += 1\n        \n    for lr in range(left, right + 1): \n        arr[lr] = temp_arr[lr] \n    return invcount\n"
  },
  {
    "path": "Microsoft/merge2SortedLinkedLists.py",
    "content": "{\n#Initial Template for Python 3\n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n,m = map(int, input().strip().split())\n        a = LinkedList() # create a new linked list 'a'.\n        b = LinkedList() # create a new linked list 'b'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_b = list(map(int, input().strip().split()))\n        for x in nodes_a:\n            a.append(x)\n        for x in nodes_b:\n            b.append(x)\n        a.head = merge(a.head,b.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to merge two sorted lists in one\n\tusing constant space.\n\t\n\tFunction Arguments: head_a and head_b (head reference of both the sorted lists)\n\tReturn Type: head of the obtained list after merger.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n\tContributed By: Nagendra Jha\n'''\ndef merge(head_a,head_b):\n    #code here\n    global a\n    elements = []\n    curr_node = head_a\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    curr_node = head_b\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    elements = sorted(elements)\n    a = LinkedList()\n    for i in elements:\n        a.append(i)\n    return a.head"
  },
  {
    "path": "Microsoft/relativeSorting.py",
    "content": "def relativeSorting(A1,A2):\n    common_elements = set(A1).intersection(set(A2))\n    extra = set(A1).difference(set(A2))\n    out = []\n    for i in A2:\n        s = [i] * A1.count(i)\n        out.extend(s)\n    extra_out = []\n    for j in extra:\n        u = [j] * A1.count(j)\n        extra_out.extend(u)\n    out = out + sorted(extra_out)\n    return \" \".join(str(i) for i in out)\n    \nif __name__ == '__main__':\n    t = int(input())\n    for tcase in range(t):\n        N,M = list(map(int,input().strip().split()))\n        A1 = list(map(int,input().strip().split()))\n        A2 = list(map(int,input().strip().split()))\n        print (relativeSorting(A1,A2))"
  },
  {
    "path": "Morgan-Stanley/addTwoNumbers_LinkedListRep.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n# prints the elements of linked list starting with head\ndef printList(head):\n    if head is None:\n        print(' ')\n        return\n    curr_node = head\n    while curr_node:\n        print(curr_node.data,end=\" \")\n        curr_node=curr_node.next\n    print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n_a = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_a = nodes_a[::-1] # reverse the input array\n        for x in nodes_a:\n            a.append(x)  # add to the end of the list\n        n_b =int(input())\n        b = LinkedList()  # create a new linked list 'b'.\n        nodes_b = list(map(int, input().strip().split()))\n        nodes_b = nodes_b[::-1]  # reverse the input array\n        for x in nodes_b:\n            b.append(x)  # add to the end of the list\n        result_head = addBoth(a.head,b.head)\n        printList(result_head)\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to add two numbers represented \n\tin the form of the linked list.\n\t\n\tFunction Arguments: head_a and head_b (heads of both the linked lists)\n\tReturn Type: head of the resultant linked list.\n    \n    __>IMP : numbers are represented in reverse in the linked list.\n    Ex:\n        145 is represented as  5->4->1.\n    \n    resultant head is expected in the same format.\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n'''\ndef addBoth(head_a,head_b):\n    #code here\n    result = LinkedList()\n    num1 = \"\"\n    curr_node = head_a\n    while curr_node != None:\n        num1 += str(curr_node.data)\n        curr_node = curr_node.next\n    num1 = num1[::-1]\n    num2 = \"\"\n    curr_node = head_b\n    while curr_node != None:\n        num2 += str(curr_node.data)\n        curr_node = curr_node.next\n    num2 = num2[::-1]\n    num = int(num1) + int(num2)\n    num = str(num)[::-1]\n    for i in num:\n        result.append(i)\n    return result.head"
  },
  {
    "path": "Myntra/countOfInversionsArray.py",
    "content": "# GeeksForGeeks Code - Copied#\n{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for tt in range(t):\n        n = int(input())\n        a = list(map(int, input().strip().split()))\n        print(Inversion_Count(a,n))\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to return total number of inversions\n\tpresent in the array.\n\t\n\tFunction Arguments: array a and size n\n\tReturn Type: Integer \n'''\ndef Inversion_Count(arr,n):\n    if a == sorted(a):\n        return 0\n    temp_arr = [0]*n\n    return mergesort(arr,temp_arr,0,n-1)\n    \ndef mergesort(arr,temp_arr,left,right):\n    inv_count = 0\n    if left < right:\n        mid = (left + right)//2\n        inv_count = mergesort(arr,temp_arr,left,mid)\n        inv_count += mergesort(arr,temp_arr,mid+1,right)\n        inv_count += merge(arr,temp_arr,left,mid,right)\n    return inv_count\n    \ndef merge(arr,temp_arr,left, mid, right): \n    # Merge the temp arrays back into arr[l..r] \n    i = left     # Initial index of first subarray \n    j = mid+1     # Initial index of second subarray \n    k = left     # Initial index of merged subarray \n    invcount = 0\n    while i <= mid and j <= right: \n        if arr[i] <= arr[j]:\n            temp_arr[k] = arr[i] \n            i += 1\n        else: \n            temp_arr[k] = arr[j]\n            invcount += (mid - i + 1)\n            j += 1\n        k += 1\n    # Copy the remaining elements of L[], if there \n    # are any \n    while i <= mid: \n        temp_arr[k] = arr[i] \n        i += 1\n        k += 1\n    # Copy the remaining elements of R[], if there \n    # are any \n    while j <= right: \n        temp_arr[k] = arr[j] \n        j += 1\n        k += 1\n        \n    for lr in range(left, right + 1): \n        arr[lr] = temp_arr[lr] \n    return invcount\n"
  },
  {
    "path": "Myntra/removeDuplicatesSortedLinkedList.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\n    \nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes = list(map(int, input().strip().split()))\n        for x in nodes:\n            a.append(x)\n        removeDuplicates(a.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to remove duplicates from given \n\tsorted linked list.\n\t\n\tFunction Arguments: head (head of the given linked list) \n\tReturn Type: none, just remove the duplicates from the list.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n'''\ndef removeDuplicates(head):\n    #code here\n    global a\n    curr_node = head\n    duplicateTracker = []\n    while curr_node != None:\n        if curr_node.data not in duplicateTracker:\n            duplicateTracker.append(curr_node.data)\n        curr_node = curr_node.next\n    a = LinkedList()\n    for x in duplicateTracker:\n        a.append(x)"
  },
  {
    "path": "Nagarro/isAnagram.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__=='__main__':\n    t = int(input())\n    for i in range(t):\n        a,b=map(str,input().strip().split())\n        if(isAnagram(a,b)):\n            print(\"YES\")\n        else:\n            print(\"NO\") \n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''Your task is to check given two strings\n   are anagrams or not.\n   a,b: given strings\n   \n   Return True or False accordingly.\n   \n   -> You don't need to print anything.Return type of function\n   is boolean.\n'''\ndef isAnagram(a,b):\n    #code here\n    import collections\n    freqs_a = collections.Counter(a)\n    freqs_b = collections.Counter(b)\n    if (set(a) == set(b)) and (sorted(freqs_a.values()) == sorted(freqs_b.values())):\n        return True\n    else:\n        return False"
  },
  {
    "path": "Nielsen/README.md",
    "content": "## Interview process for Senior SDE roles (Personal Experience)  \n1. BarRaiser Round.  \n2. Technical Interview rounds if BarRaiser is passed.\n   - Technical Deep dive on projects listed in the CV - Questions on scalability of the architectures, pipelines, AWS cost saving opportunities etc.  \n   - Coding questions on Arrays related to combinatorial optimization concepts.  \n"
  },
  {
    "path": "OYO_Rooms/FindzeroSumSubArrays.py",
    "content": "def subArrayExists(arr,n):\n    ##Your code here\n    hashMap = {}\n    out = []\n    sum1 = 0\n    for i in range(n):\n        sum1 += arr[i]\n        if sum1==0:\n            out.append((0,i))\n        al = []\n        if sum1 in hashMap:\n            al = hashMap.get(sum1)\n            for it in range(len(al)):\n                out.append((al[it]+1,i))\n        al.append(i)\n        hashMap[sum1] = al\n    return len(out)\n    \n    \nif __name__ == '__main__':\n    t = int(input())\n    for tcase in range(t):\n        n = int(input())\n        arr = list(map(int,input().strip().split()))\n        print (subArrayExists(arr,n))"
  },
  {
    "path": "OYO_Rooms/parenthesisChecker.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n#Contributed by : Nagendra Jha\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    test_cases = int(input())\n    for cases in range(test_cases) :\n        #n = int(input())\n        #n,k = map(int,imput().strip().split())\n        #a = list(map(int,input().strip().split()))\n        s = str(input())\n        if ispar(s):\n            print(\"balanced\")\n        else:\n            print(\"not balanced\")\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\nFunction Arguments :\n\t\t@param  : s (given string containing parenthesis) \n\t\t@return : boolean True or False\n'''\n\ndef isMatchingPair(c1,c2):\n    if (c1=='(') & (c2==')'):\n        return True\n    elif (c1=='{') & (c2=='}'):\n        return True\n    elif (c1=='[') & (c2==']'):\n        return True\n    else:\n        return False\n        \ndef ispar(s):\n    # code here\n    import queue\n    stack = queue.LifoQueue()\n    \n    for i in range(len(s)):\n        if ((s[i] == '{') | (s[i] == '[') | (s[i] == '(')):\n            stack.put(s[i])\n        if ((s[i] == '}') | (s[i] == ']') | (s[i] == ')')):\n            if stack.empty():\n                return False\n            elif not isMatchingPair(stack.get(),s[i]):\n                return False\n        \n    if stack.empty():\n        return True\n    else:\n        return False"
  },
  {
    "path": "OYO_Rooms/removeDuplicatesSortedLinkedList.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\n    \nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes = list(map(int, input().strip().split()))\n        for x in nodes:\n            a.append(x)\n        removeDuplicates(a.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to remove duplicates from given \n\tsorted linked list.\n\t\n\tFunction Arguments: head (head of the given linked list) \n\tReturn Type: none, just remove the duplicates from the list.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n'''\ndef removeDuplicates(head):\n    #code here\n    global a\n    curr_node = head\n    duplicateTracker = []\n    while curr_node != None:\n        if curr_node.data not in duplicateTracker:\n            duplicateTracker.append(curr_node.data)\n        curr_node = curr_node.next\n    a = LinkedList()\n    for x in duplicateTracker:\n        a.append(x)"
  },
  {
    "path": "Oracle/merge2SortedLinkedLists.py",
    "content": "{\n#Initial Template for Python 3\n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n,m = map(int, input().strip().split())\n        a = LinkedList() # create a new linked list 'a'.\n        b = LinkedList() # create a new linked list 'b'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_b = list(map(int, input().strip().split()))\n        for x in nodes_a:\n            a.append(x)\n        for x in nodes_b:\n            b.append(x)\n        a.head = merge(a.head,b.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to merge two sorted lists in one\n\tusing constant space.\n\t\n\tFunction Arguments: head_a and head_b (head reference of both the sorted lists)\n\tReturn Type: head of the obtained list after merger.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n\tContributed By: Nagendra Jha\n'''\ndef merge(head_a,head_b):\n    #code here\n    global a\n    elements = []\n    curr_node = head_a\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    curr_node = head_b\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    elements = sorted(elements)\n    a = LinkedList()\n    for i in elements:\n        a.append(i)\n    return a.head"
  },
  {
    "path": "Paytm/Convert_Infix_To_Postfix.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n# This code is contributed by Nikhil Kumar Singh(nickzuck_007)\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    test_cases = int(input())\n    for cases in range(test_cases) :\n        exp = str(input())\n        print(InfixtoPostfix(exp))\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\nFunction Arguments :\n\t\t@param  : exp (given infix expression)\n\t\t@return : string\n'''\ndef InfixtoPostfix(exp):\n    #code here\n    import string\n    stack = []\n    prec = {'^':4,'*':3,'/':3,'+':2,'-':2,'(':1}\n    postfixexp = []\n    tokens = list(exp)\n    for token in tokens:\n        if ((token in string.ascii_lowercase) | (token in \"0123456789\") | (token in string.ascii_uppercase)):\n            postfixexp.append(token)\n        elif token == '(':\n            stack.append(token)\n        elif token == ')':\n            if len(stack)!=0:\n                topToken = stack.pop()\n                while topToken != '(':\n                    postfixexp.append(topToken)\n                    topToken = stack.pop()\n        else:\n            if len(stack) != 0:\n                while (len(stack)!=0) and (prec[stack[-1]] >= prec[token]):\n                    postfixexp.append(stack.pop())\n            stack.append(token)\n    while len(stack)!=0:\n        postfixexp.append(stack.pop())\n    return \"\".join(postfixexp)"
  },
  {
    "path": "Paytm/binaryArraySort.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            N=int(input())\n            A=list(map(int,input().split()))\n            \n            binSort(A,N)\n            \n            for i in A:\n                print(i,end=\" \")\n            print()\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n##Complete this function\ndef binSort(arr, n): \n    #Your code here\n    \n    \n    '''\n    No need to print the array\n    '''\n    c0 = arr.count(0)\n    c1 = arr.count(1)\n    for i in range(c0):\n        arr[i] = 0\n    for i in range(c0,c0+c1):\n        arr[i] = 1"
  },
  {
    "path": "Paytm/frequencyLimitedRangeArrayElements.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n    \n    T=int(input())\n    \n    while(T>0):\n        \n        \n        N=int(input())\n        \n        A=[int(x) for x in input().strip().split()]\n        printfrequency(A,N)\n        \n        print()\n        \n        T-=1\nif __name__==\"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef printfrequency(A,N):\n    #Your Code here\n    import collections\n    freq_dict = collections.Counter(A)\n    for i in range(1,N+1):\n        print (freq_dict[i],end=\" \")"
  },
  {
    "path": "Paytm/subarrayWithZeroSum.py",
    "content": "{\n#Initial Template for Python 3\ndef main():\n    T=int(input())\n    while(T>0):\n        \n        n=int(input())\n        arr=[int(x) for x in input().strip().split()]\n        if(subArrayExists(arr,n)):\n            print(\"Yes\")\n        else:\n            print(\"No\")\n        \n        \n        T-=1\nif __name__==\"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\n\ndef allSubArrays(L,L2=None):\n    if L2==None:\n        L2 = L[:-1]\n    if L==[]:\n        if L2==[]:\n            return []\n        return allSubArrays(L2,L2[:-1])\n    return [L]+allSubArrays(L[1:],L2)\n    \ndef subArrayExists(arr,n):\n    ##Your code here\n    #Return true or false\n    if 0 in arr:\n        return True\n    else:\n        allsubarrays = allSubArrays(arr)\n        for s in allsubarrays:\n            if sum(s) == 0:\n                return True\n    return False"
  },
  {
    "path": "Qalcomm/ImplementSTRSTR.py",
    "content": "{\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        s,p =input().strip().split()\n        print(strstr(s,p))\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n'''\n\tYour task is to return the index of the pattern\n\tpresent in the given string.\n\t\n\tFunction Arguments: s (given text), p(given pattern)\n\tReturn Type: Integer.\n\t\n'''\ndef strstr(s,p):\n    #code here\n    import re\n    loc = re.search(p,s)\n    if loc is not None:\n        return (loc.start())\n    else:\n        return -1"
  },
  {
    "path": "Qalcomm/addTwoNumbers_LinkedListRep.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n# prints the elements of linked list starting with head\ndef printList(head):\n    if head is None:\n        print(' ')\n        return\n    curr_node = head\n    while curr_node:\n        print(curr_node.data,end=\" \")\n        curr_node=curr_node.next\n    print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n_a = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_a = nodes_a[::-1] # reverse the input array\n        for x in nodes_a:\n            a.append(x)  # add to the end of the list\n        n_b =int(input())\n        b = LinkedList()  # create a new linked list 'b'.\n        nodes_b = list(map(int, input().strip().split()))\n        nodes_b = nodes_b[::-1]  # reverse the input array\n        for x in nodes_b:\n            b.append(x)  # add to the end of the list\n        result_head = addBoth(a.head,b.head)\n        printList(result_head)\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to add two numbers represented \n\tin the form of the linked list.\n\t\n\tFunction Arguments: head_a and head_b (heads of both the linked lists)\n\tReturn Type: head of the resultant linked list.\n    \n    __>IMP : numbers are represented in reverse in the linked list.\n    Ex:\n        145 is represented as  5->4->1.\n    \n    resultant head is expected in the same format.\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n'''\ndef addBoth(head_a,head_b):\n    #code here\n    result = LinkedList()\n    num1 = \"\"\n    curr_node = head_a\n    while curr_node != None:\n        num1 += str(curr_node.data)\n        curr_node = curr_node.next\n    num1 = num1[::-1]\n    num2 = \"\"\n    curr_node = head_b\n    while curr_node != None:\n        num2 += str(curr_node.data)\n        curr_node = curr_node.next\n    num2 = num2[::-1]\n    num = int(num1) + int(num2)\n    num = str(num)[::-1]\n    for i in num:\n        result.append(i)\n    return result.head"
  },
  {
    "path": "Quikr/BuySellStock.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            n=int(input())\n            \n            arr=[int(x) for x in input().strip().split()]\n            stockBuySell(arr,n)\n            print()\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef stockBuySell(A,n):\n    if A == sorted(A):\n        print (\"(\" + str(0) + \" \" + str(n-1) + \")\",end=\" \")\n    elif A == sorted(A,reverse=True):\n        print (\"No Profit\",end = \" \")\n    else:\n        local_min = []\n        local_max = []\n        for i,v in enumerate(A):\n            if i == 0:\n                if v < A[i+1]:\n                    local_min.append(i)\n            elif i == n-1:\n                if v > A[i-1]:\n                    local_max.append(i)\n            else:\n                if A[i-1] <= v and v >= A[i+1]:\n                    local_max.append(i)\n                if A[i-1] >= v and v <= A[i+1]:\n                    local_min.append(i)\n        if len(local_max) == len(local_min):\n            for i in range(len(local_max)):\n                x = \" \".join([str(local_min[i]),str(local_max[i])])\n                print (\"(\"+x+\")\",end=\" \")\n        else:\n            x = \" \".join([str(max(local_min)),str(max(local_max))])\n            print (\"(\"+x+\")\",end = \" \")"
  },
  {
    "path": "README.md",
    "content": "# Programming questions/Case studies/Theoretical questions/Design questions etc From Interviews and Coding Tests:  \n  \n+ Interview Coding Questions for Several Companies encapsulated into one Repository.  \n+ Coding questions asked in private hiring processes.  \n+ Statistics and questions on Data science for Data scientist interviews.  \n+ Along with coding questions, interview procedures experienced are also included here.  \n+ **Please note that some of these questions are from my own experiences with various companies (check README for that information), please create an issue if you have any questions regarding any company and its questions.**   \n+ **I update this repo with additions as I go through the process of hiring (You can imagine this as kind of a blog), so sometimes even if I didn't make it till the end of the whole process you can expect the questions till the point I was there, My intention is to help the community of software developers.**  \n+ **This repository and [Coding Questions](https://github.com/absognety/Competitive-Coding-Platforms) can have few common questions**  \n+ Check out my effort in solving questions from daily coding problem (Daily coding quesitons sent to your email) at [Here](https://github.com/absognety/Competitive-Coding-Platforms/tree/master/DailyCodingProblem).  \n  \nFeel free to contribute to this repo and make this one of the best open source resources for interview preparations!!!!  \n# <ins>Disclaimer: This repository might document the interview processes of latest up and coming companies which could lead to interview privacy concerns - I trust the user discretion for this</ins>.  \nPlease note that the interview questions and process bound to change at any point of time - but If this repository helped you, Please give a star.  \n"
  },
  {
    "path": "RelianceJIO/CamelCaseToSnakeCase.py",
    "content": "#!/usr/bin/python3.8\n\"\"\"\n\nWrite a function that converts camel_case string into snake case:\n    \n    Example:\n        \n        HackerEarth => hacker_earth\n        OddOrEven => odd_or_even\n        macOS => mac_o_s\n        primeCheck => prime_check\n        \n    Explanation:\n        Camel case string is string with uppercase and lowercase characters\n        mixed up like illustrated above\n        \n        Snake case strings are lowercase with underscores in place of uppercase\n        characters which are in the middle\n\n\"\"\"\nimport re\ndef convert_string(s:str) -> str:\n    store_indices = []\n    slist = list(s)\n    for ind,val in enumerate(s):\n        if val.isupper() and ind!=0:\n            store_indices.append(ind)\n            \n    c = len(store_indices)\n    l = 0\n    while (l <= c-1):\n        slist.insert(store_indices[l]+l,'_')\n        l += 1\n    return ''.join(slist).lower()\n\n\nif __name__ == '__main__':\n    for tcase in range(T:=int(input())):\n        s = input()\n        print (convert_string(s))\n"
  },
  {
    "path": "RelianceJIO/README.md",
    "content": "# First round:  \n## Hackerrarth Test with some data science questions (Objective) along with 2 coding question  \n"
  },
  {
    "path": "RelianceJIO/getSmallestNumber.py",
    "content": "#!/usr/bin/python3.8\n\n\"\"\"\nP(N) gives all the numbers that divide given number N\n\nfind the smallest number number Y such that Y > X and P(Y) != P(X), given \nnumber X\n\"\"\"\nimport math\ndef div_count(n):\n    # sieve method for \n    # prime calculation \n    hh = [1] * (n + 1); \n      \n    p = 2\n    while((p * p) < n): \n        if (hh[p] == 1): \n            for i in range((p * 2), n, p): \n                hh[i] = 0\n        p += 1\n  \n    # Traversing through  \n    # all prime numbers \n    total = 1\n    for p in range(2, n + 1): \n        if (hh[p] == 1): \n  \n            # calculate number of divisor \n            # with formula total div =  \n            # (p1+1) * (p2+1) *.....* (pn+1) \n            # where n = (a1^p1)*(a2^p2)....  \n            # *(an^pn) ai being prime divisor \n            # for n and pi are their respective  \n            # power in factorization \n            count = 0\n            if (n % p == 0): \n                while (n % p == 0): \n                    n = int(n / p)\n                    count += 1\n                total *= (count + 1)\n                  \n    return total\n\n\ndef smallestNumber(n,ndn):\n    MAX_INT = math.inf\n    p = n + 1\n    while (p < MAX_INT):\n        if div_count(p) != ndn:\n            break\n        p += 1\n    return p\n\nif __name__ == '__main__':\n    for tcase in range(T:=int(input())):\n        n = int(input())\n        print (smallestNumber(n, ndn=div_count(n)))"
  },
  {
    "path": "Salesforce/BuySellStock.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            n=int(input())\n            \n            arr=[int(x) for x in input().strip().split()]\n            stockBuySell(arr,n)\n            print()\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef stockBuySell(A,n):\n    if A == sorted(A):\n        print (\"(\" + str(0) + \" \" + str(n-1) + \")\",end=\" \")\n    elif A == sorted(A,reverse=True):\n        print (\"No Profit\",end = \" \")\n    else:\n        local_min = []\n        local_max = []\n        for i,v in enumerate(A):\n            if i == 0:\n                if v < A[i+1]:\n                    local_min.append(i)\n            elif i == n-1:\n                if v > A[i-1]:\n                    local_max.append(i)\n            else:\n                if A[i-1] <= v and v >= A[i+1]:\n                    local_max.append(i)\n                if A[i-1] >= v and v <= A[i+1]:\n                    local_min.append(i)\n        if len(local_max) == len(local_min):\n            for i in range(len(local_max)):\n                x = \" \".join([str(local_min[i]),str(local_max[i])])\n                print (\"(\"+x+\")\",end=\" \")\n        else:\n            x = \" \".join([str(max(local_min)),str(max(local_max))])\n            print (\"(\"+x+\")\",end = \" \")"
  },
  {
    "path": "Samsung/merge2SortedLinkedLists.py",
    "content": "{\n#Initial Template for Python 3\n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n,m = map(int, input().strip().split())\n        a = LinkedList() # create a new linked list 'a'.\n        b = LinkedList() # create a new linked list 'b'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_b = list(map(int, input().strip().split()))\n        for x in nodes_a:\n            a.append(x)\n        for x in nodes_b:\n            b.append(x)\n        a.head = merge(a.head,b.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to merge two sorted lists in one\n\tusing constant space.\n\t\n\tFunction Arguments: head_a and head_b (head reference of both the sorted lists)\n\tReturn Type: head of the obtained list after merger.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n\tContributed By: Nagendra Jha\n'''\ndef merge(head_a,head_b):\n    #code here\n    global a\n    elements = []\n    curr_node = head_a\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    curr_node = head_b\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    elements = sorted(elements)\n    a = LinkedList()\n    for i in elements:\n        a.append(i)\n    return a.head"
  },
  {
    "path": "Samsung/missingSmallestPositiveNumber.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            n=int(input())\n            \n            arr=[int(x) for x in input().strip().split()]\n            \n            print(missingNumber(arr,n))\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n##Complete this function\ndef missingNumber(arr,n):\n    #Your code here\n    poss = [x for x in arr if x > 0]\n    if poss:\n        if poss == list(range(1,n+1)):\n            return max(poss)+1\n        else:\n            min_poss = min(poss)\n            max_poss = max(poss)\n            total_range = list(range(1,max_poss+1))\n            missingNumbers = set(total_range) - set(poss)\n            return min(missingNumbers)\n    else:\n        return 0"
  },
  {
    "path": "Samsung/moveAllZerosToEndOfArray.py",
    "content": "def moveZerosToEnd(arr):\n    arr_0 = [x for x in arr if x!=0]\n    zeros = [0] * (len(arr)-len(arr_0))\n    ans = arr_0 + zeros\n    return \" \".join(str(u) for u in ans)\n\nif __name__ == '__main__':\n    T = int(input())\n    for t in range(T):\n        N = int(input())\n        arr = list(map(int,input().strip().split()))\n        print (moveZerosToEnd(arr))"
  },
  {
    "path": "SkyPointCloud/README.md",
    "content": "# Interview process for skypoint cloud (Data engineer) (Personal Experience):  \n1. **Hackerearth Test**: objective questions on hadoop, spark, python and airflow basics and one coding question added above.  \n2. **First round of Interview**:  \n   - Questions:  \n     - what is the difference between mapreduce and spark?  \n     - What is the difference between Spark `coalesce` and `repartition`?  \n     - How do you handle out of memory error in spark application execution?  \n     - How does pyspark work?  \n     - Can you explain how you solved the programming question you have solved in the test? (refer [here](https://github.com/absognety/Interview-Process-Coding-Questions/blob/master/SkyPointCloud/modifyString.py))  \n3. **Second round of Interview**:  \n   - Questions:\n     - what are the challenges you encountered in your projects and how did you solve them?\n     - **Case Study**:  \n       - Let's say there are 3 data sources(RDBMS), First Data source contains (firstname,lastname,email and gender), second one contains (firstname,lastname,order_history) and third contains (email,profile_id). How can you construct a 360 degrees view of a customer that contains all information from 3 data sources containing (firstname,lastname,email,gender,order_history and profile_id) but without traditional way of joining the columns (looking for more of ML based solution)(Hint: the columns may contain special characters, spaces, underscores etc)\n     - What are list comprehensions and dictionary comprehensions in python.  \n     - Tell me one approach on finding all prime numbers in the given range?  \n     - Can you code up a binary search algorithm in array that is sorted in descending order? (refer [here](https://github.com/absognety/Interview-Process-Coding-Questions/blob/master/SkyPointCloud/binarySearch.py))  \n     - How do you define/create a class in python?  \n4. **Final round of interview with Founder/CEO**.  \n"
  },
  {
    "path": "SkyPointCloud/binarySearch.py",
    "content": "\"\"\"\nCan you write the binary search algorithm for reverse sorted array?\n\n\"\"\"\ndef binarySearch(arr,x):\n    arr = sorted(arr,reverse=True)\n    l = 0\n    r = len(arr) - 1\n  \n    while l <= r: \n  \n        mid = l + (r - l) // 2; \n          \n        # Check if x is present at mid \n        if arr[mid] == x: \n            return mid \n   \n        elif arr[mid] > x: \n            l = mid + 1\n  \n        else: \n            r = mid - 1\n      \n    # If we reach here, then the element \n    # was not present \n    return \"not present\"\n\nif __name__ == '__main__':\n    mylist = [1,3,5,7,9,8,5,88,79]\n    n = len(mylist)\n    print (binarySearch(mylist,5))\n    print (binarySearch(mylist,88))\n    print (binarySearch(mylist,79))\n    print (binarySearch(mylist,20))\n    print (binarySearch(mylist,1))"
  },
  {
    "path": "SkyPointCloud/modifyString.py",
    "content": "\"\"\"\nGiven a string, sort/modify the characters of string according to below rules:\n    \n    1. characters having prime ascii values should come before characters\n    having composite ascii values.\n    \n    2. if two characters have same prime ascii value, then the character with\n    less value should come first.\n    \n    3. if two characters have same composite ascii value, then the character\n    with greater value should come first\n    \n\"\"\"\n\ndef isPrime(n) : \n  \n    # Corner cases \n    if (n <= 1) : \n        return False\n    if (n <= 3) : \n        return True\n  \n    # This is checked so that we can skip  \n    # middle five numbers in below loop \n    if (n % 2 == 0 or n % 3 == 0) : \n        return False\n  \n    i = 5\n    while(i * i <= n) : \n        if (n % i == 0 or n % (i + 2) == 0) : \n            return False\n        i = i + 6\n  \n    return True\n\ndef sort_string(s,n):\n    prime_chars = []\n    composite_chars = []\n    for c in s:\n        if isPrime(ord(c)):\n            prime_chars.append(c)\n        else:\n            composite_chars.append(c)\n    prime_dict = [(c,ord(c)) for c in prime_chars]\n    composite_dict = [(d,ord(d)) for d in composite_chars]\n    prime_dict = sorted(prime_dict,key=lambda x: x[1])\n    composite_dict = sorted(composite_dict,key=lambda y:y[1],reverse=True)\n    result = [k1 for k1,v1 in prime_dict] + [k2 for k2,v2 in composite_dict]\n    return ''.join(result)\n\nif __name__ == '__main__':\n    n = int(input())\n    s = input()\n    print (sort_string(s,n))"
  },
  {
    "path": "Snapdeal/addTwoNumbers_LinkedListRep.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n# prints the elements of linked list starting with head\ndef printList(head):\n    if head is None:\n        print(' ')\n        return\n    curr_node = head\n    while curr_node:\n        print(curr_node.data,end=\" \")\n        curr_node=curr_node.next\n    print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n_a = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_a = nodes_a[::-1] # reverse the input array\n        for x in nodes_a:\n            a.append(x)  # add to the end of the list\n        n_b =int(input())\n        b = LinkedList()  # create a new linked list 'b'.\n        nodes_b = list(map(int, input().strip().split()))\n        nodes_b = nodes_b[::-1]  # reverse the input array\n        for x in nodes_b:\n            b.append(x)  # add to the end of the list\n        result_head = addBoth(a.head,b.head)\n        printList(result_head)\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to add two numbers represented \n\tin the form of the linked list.\n\t\n\tFunction Arguments: head_a and head_b (heads of both the linked lists)\n\tReturn Type: head of the resultant linked list.\n    \n    __>IMP : numbers are represented in reverse in the linked list.\n    Ex:\n        145 is represented as  5->4->1.\n    \n    resultant head is expected in the same format.\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n'''\ndef addBoth(head_a,head_b):\n    #code here\n    result = LinkedList()\n    num1 = \"\"\n    curr_node = head_a\n    while curr_node != None:\n        num1 += str(curr_node.data)\n        curr_node = curr_node.next\n    num1 = num1[::-1]\n    num2 = \"\"\n    curr_node = head_b\n    while curr_node != None:\n        num2 += str(curr_node.data)\n        curr_node = curr_node.next\n    num2 = num2[::-1]\n    num = int(num1) + int(num2)\n    num = str(num)[::-1]\n    for i in num:\n        result.append(i)\n    return result.head"
  },
  {
    "path": "Swiggy/README.md",
    "content": "# Personal Experience - Software Development Engineer - II (Data and ML Platform):  \n  \n## First Round (Computer Science Fundamentals and DSA):   \n- Let's assume there are N number of lines in 2D coordinate system and their start and end points - `(X1s,X1e),(X2s,X2e),......(XNs,XNe) where s = start and e = end`, we need to draw a line perpendicular to X-axis (Parallel to Y-axis) such that the line intersects maximum number of given lines and also find the points of intersection if possible (If multiple intersection points possible that maximizes number of intersections - return any of them).  \n- Find the second largest element in an array?\n- When does the shuffling happen in spark?\n- what's your inference on the scenario where the application is running and memory consumption is too high and CPU utilization is constant?\n- what are `coalesce` and `repartition` in Spark?\n- How does the parallelism happen in Python? Methods to deal with and questions on relevant libraries?  \n\n## Second Round (DSA):  \n- Code up a linkedlist with all necessary operations from scratch!  \n- Questions on developed linkedlist code, execution and manipulations to the code for some questions.  \n- Find the middle element of the linkedlist.  \n- Detect a cycle in the linkedlist if present.\n- Doubly linkedlists and cyclic linkedlists - Questions only (No need to implement).  \n- Questions on Internals of Spark and performance related questions.  \n\n## LLD (Low Level Design Round):  \n- Given a scenario of ATC (Air Traffic Controller) and flights, Questions on interactions between flight pilot and ATC if ATC needs to replaced with a automated system (Answer expected interms of API lingo) - payload, messages exchange, queues, parameters - etc.  \n- Design a low level ATC system that manages the flight traffic, departures and arrivals within 50 kms of radius.  \n"
  },
  {
    "path": "SymphonyAI/README.md",
    "content": "Hackerrank Test (Personal Experience) (2020) \n===========================================\n______________________________________________________________________________________________\n\n# Interview Experience (NLP Systems Engineer) - 2021:  \n### First Round:  \n+ Simple programming and statistics based questions using numpy,scipy etc.  \n+ Quesitons on pyspark vs scala-spark\n+ what kind of Data warehouse architecture are you using in your company? Questions on that as well.  \n\n### Second Round:  \n+ Random forest vs XGBoost\n+ Questions on decision tree internals and how does it work end-end?  \n+ Model evaluation and selection techniques and questions on that involving confusion matrix etc.  \n+ Questions on K-Fold cross validation and other model validation strategies.  \n+ Model overfitting and Underfitting - How do you know?  \n+ Questions on NLP project that you did.  \n+ Programming question based on sorting (sorting strings in lexographical order) without using any libraries or built-in functions.  \n+ `inplace` and `axis` arguments in pandas apis.  \n"
  },
  {
    "path": "SymphonyAI/maximumHeightOfMudSegment.py",
    "content": "\"\"\"\nProblem Statement\nA child likes to build mud walls by placing mud between sticks positioned on \na number line. The gap between sticks will be referred to as a cell, and \neach cell will contain one segment of wall. The height of mud in a segment \ncannot exceed 1 unit above an adjacent stick or mud segment. Given the \nplacement of a number of sticks and their heights, determine the maximum \nheight segment of mud that can be built. If no mud segment can be built, \nreturn 0.\n\nFor example, there are n = 3 sticks at stickPositions = [1, 2, 4, 7] with s\ntickHeights = [4, 5, 7, 11]. There is no space between the first two sticks, \nso there is no cell for mud. Between positions 2 and 4, there is one cell. \nHeights of the surrounding sticks are 5 and 7, so the maximum height of mud \nis 5 + 1 = 6. Between positions 4 and 7 there are two cells. The heights of \nsurrounding sticks are 7 and 11. The maximum height mud segment next to the \nstick of height 7 is 8. The maximum height mud next to a mud segment of \nheight 8 and a stick of height 11 is 9. Mud segment heights are 6, 8 and 9, \nand the maximum height is 9. In the table below, digits are in the columns \nof sticks and M is in the mud segments.\n\n      7\n      7\n     M7\n    MM7\n   4MM7\n  M4MM7\n 2M4MM7\n12M4MM7\n12M4MM7\n12M4MM7\n12M4MM7\nFunction Description\nComplete the function maxHeight in the editor below. The function must \nreturn an integer, the maximum height mud segment that can be built.\n\nmaxHeight has the following parameter(s):\nstickPositions[stickPositions[0],…stickPositions[n-1]]: an array of integers\nstickHeights[stickHeights[0],…stickHeights[n-1]]: an array of integers\n\nConstraints\n1 ≤ n ≤ 105\n1 ≤ stickPositions[i] ≤ 109 (where 0 ≤ i < n)\n1 ≤ stickHeights[i] ≤ 109 (where 0 ≤ i < n)\n\nSample Input For Custom Testing\n\n3\n1\n3\n7\n3\n4\n3\n3\nSample Output\n\n5\nExplanation\n\n    M\n1M MMM\n1M3MMM7\n1M3MMM7\n1M3MMM7\nHere stickPositions = [1, 3, 7] and stickHeights = [4, 3, 3]. There can be a \nsegment of height 4 at position 2 supported by sticks of heights 4 and 3. \nBetween positions 3 and 7, there can be a segment of height 4 at positions 4 \nand 6. Between them, a segment can be built of height 5 at position 5.\n\n\n\"\"\"\n\ndef maxHeight(wallPositions,wallHeights):\n    n = len(wallPositions)\n    maxim = 0\n    for i in range(n-1):\n        if wallPositions[i] < wallPositions[i+1]-1:\n            heightDiff = abs(wallHeights[i+1]-wallHeights[i])\n            gapLen = wallPositions[i+1]-wallPositions[i]-1\n            localMax = 0\n            if gapLen > heightDiff:\n                low = max(wallHeights[i+1],wallHeights[i]) + 1\n                remainingGap = gapLen - heightDiff - 1\n                localMax = low + remainingGap//2\n            else:\n                localMax = min(wallHeights[i+1],wallHeights[i]) + gapLen\n            maxim = max(maxim,localMax)\n    return maxim\n\n\nif __name__ == '__main__':\n    wallPositions = [1,2,4,7]\n    wallHeights = [4,6,8,11]\n    print (maxHeight(wallPositions=wallPositions,wallHeights=wallHeights))\n    wallPositions = [1,3,7]\n    wallHeights = [4,3,3]\n    print (maxHeight(wallPositions,wallHeights))"
  },
  {
    "path": "Tavant-Technologies/README.md",
    "content": "## Interview with Senior Technical Architect (Glider discussion):  \n1. One Simple Coding question:\n   - Given a list of candidates (list of names - there can be a name repeating).Number of times the candidate's name is repeating is his votes. So, find the candidate with maximum number of votes and if there is a tie then print the candidates name which is lexicographically smaller.  \n2. Variety of questions from big data projects from the CV involving workflow orchestration,Hive,Hadoop\n3. Given a scenario, your knowledge on designing systems is tested aggressively from solutioning approach to implementation.\n4. Difference between external and managed tables in hive\n5. Questions on CI/CD\n6. How would you perform testing (need specifics here!)\n7. How would a design a data ingestion framework that consumes datasets from different data sources (Assume each job of data dump from each source is scheduled at a different time), Design a system that consumes the dump with as minimum latency as possible from different sources and makes it available for different applications?  \n"
  },
  {
    "path": "Thomson-Reuters/README.md",
    "content": "# Interview Process - Personal (Machine Learning Engineer) - 2021:  \n### First Round - Hackerrank test:  \n+ Given a string, coding question on text preprocessing (cleaning text into corpus) - removing extra characters,removing stopwords, punctuations,text normalization techniques.  \n+ Given a string, coding question on string tokenization, text cleaning techniques (identify numbers,removing words having numbers,identify words with a pattern etc.).  \n+ Multiple choice questions on Machine learning - Model overfitting and underfitting, data leakage, supervised vs unsupervised learning, loss functions, cost minimizations, gradient descent, deep learning etc.  \n+ Multiple choice questions on AWS - AWS lambda, IAM, Cloudformation, sagemaker, billing, S3 etc. (Refer documentation of AWS).  \n"
  },
  {
    "path": "Thoughtworks/README.md",
    "content": "Source of Problem Statement for [ScheduleInterviews.py](ScheduleInterviews.py) - [link](https://github.com/YogeshSharma0201/ThoughtWorks-pair-coding-round)\n\nOriginal Solution was delivered in C++, But I have developed my own solution in Python.\n\nFYI - This solution is not a re-implementation or direct translation of code present in [link](https://github.com/YogeshSharma0201/ThoughtWorks-pair-coding-round).\n"
  },
  {
    "path": "Thoughtworks/ScheduleInterviews.py",
    "content": "from typing import List,Tuple\nimport datetime\n\ndef divideWorkingHours(start_time:datetime.datetime,\n                       end_time:datetime.datetime,\n                       interval:datetime.timedelta) -> List[Tuple]:\n    periods = []\n    period_start = start_time\n    while period_start < end_time:\n        period_end = min(period_start + interval, end_time)\n        if (period_end - period_start == interval):\n            periods.append((period_start, period_end))\n        period_start = period_end\n    return periods\n\n\ndef removeOverlaps(slots:List[Tuple],break_hour:Tuple) -> List[Tuple]:\n    refined_slots = []\n    for slot in slots:\n        latest_start = max(slot[0], break_hour[0])\n        earliest_end = min(slot[1], break_hour[1])\n        delta = (earliest_end - latest_start).days\n        if (delta < 0) or (earliest_end == latest_start):\n            refined_slots.append(slot)\n    return refined_slots\n\n\ndef scheduleInterviews(attendees:dict,\n                       interviewers:dict,\n                       rooms:dict,\n                       slots:List[Tuple]) -> List[Tuple]:\n    available_attendees = attendees.get(\"entity\").copy()\n    available_interviewers = interviewers.get(\"entity\").copy()\n    available_rooms = rooms.get(\"entity\").copy()\n    available_slots = slots[::-1].copy()\n    attendees_done_with_interview = set()\n    interviews_scheduled = list()\n    while len(available_slots) > 0:\n        while ((len(available_interviewers) > 0) & (len(available_rooms) > 0) & \n               (len(available_attendees) > 0)):\n             attendee = available_attendees[-1]\n             interviewer = available_interviewers[-1]\n             room = available_rooms[-1]\n             slot = available_slots[-1]\n             interviews_scheduled.append((slot,attendee,interviewer,room))\n             attendees_done_with_interview.add(attendee)\n             print (interviews_scheduled)\n             available_attendees.pop()\n             available_rooms.pop()\n             available_interviewers.pop()\n        available_slots.pop()\n        available_interviewers = interviewers.get(\"entity\").copy()\n        available_rooms = rooms.get(\"entity\").copy()\n        available_attendees = list(set(attendees.get(\"entity\").copy()) - attendees_done_with_interview)\n    return interviews_scheduled\n\n\nif __name__ == '__main__':\n    #Attendees\n    n_attendees = int(input())\n    attendees = list(map(int, input().strip().split(\",\")))\n    assert len(attendees) == n_attendees, \"length of attendees list does not match with declared total\"\n    #Interviewers\n    n_interviewers = int(input())\n    interviewers = list(map(str, input().strip().split(\",\")))\n    assert len(interviewers) == n_interviewers, \"length of interviewers list does not match with declared total\"\n    #Rooms\n    n_rooms = int(input())\n    rooms = list(map(str, input().strip().split(\",\")))\n    assert len(rooms) == n_rooms, \"length of rooms list does not match with declared total\"\n\n    attendees_dict = {\"entity\":attendees,\"count\":n_attendees}\n    interviewers_dict = {\"entity\":interviewers,\"count\":n_interviewers}\n    rooms_dict = {\"entity\":rooms,\"count\":n_rooms}\n    #Give all Inputs required\n    year = 2024\n    month = 1\n    day = 22\n    break_hour_start = 14\n    break_hour_end = 15\n    work_hours_start = 9\n    work_hours_end = 18\n    slot_duration_in_min = 120\n    break_hour = (datetime.datetime(year,month,day,break_hour_start,0,0),\n                  datetime.datetime(year,month,day,break_hour_end,0,0))\n    start_time = datetime.datetime(year,month,day,work_hours_start,0,0)\n    end_time = datetime.datetime(year,month,day,work_hours_end,0,0)\n    interval = datetime.timedelta(minutes=slot_duration_in_min)\n    #Run the Algorithm\n    slots = divideWorkingHours(start_time,end_time,interval)\n    refined_slots = removeOverlaps(slots=slots,break_hour=break_hour)\n    result = scheduleInterviews(attendees=attendees_dict,\n                                interviewers=interviewers_dict,\n                                rooms=rooms_dict,\n                                slots=refined_slots)\n    print (result)"
  },
  {
    "path": "Twilio/DiskSpaceAnalysis.py",
    "content": "# Number of Computers: n = 4\n# Space = [8,2,4,6]\n# x = 2, The segment length\n\n# The free disk space of computers in each of these segments is [8,2],[2,4] and [4,6]\n# The minimum of these three segments are 2, 2 and 4 - [2,2,4]\n# Maximum of these is 4\n\nfrom typing import List\nimport math\n\ndef segment(x:int, space:List[int]) -> int:\n    m,M = x-1,x\n    segments_generated = [space[i*(M-m):i*(M-m)+M] for i in range(math.ceil((len(space)-m)/(M-m)))]\n    return max([min(segment) for segment in segments_generated])\n\nif __name__ == '__main__':\n    num_computers = 7\n    space = [8,2,4,6,10,15,18]\n    segment_length = 3\n\n    print (segment(x = segment_length,\n                   space=space))"
  },
  {
    "path": "Twilio/README.md",
    "content": "### Hackerrank Test - 2020  \n  \n1. Find the area of largest square that can be found with all 1's present in a binary matrix of 1's and 0's?  \n2. Given a sentence, write a word break algorithm that breaks down sentence into number of lines (conditions apply).\n\n### Question gleaned from online: [DiskSpaceAnalysis.py](https://github.com/absognety/Interview-Process-Coding-Questions/blob/master/Twilio/DiskSpaceAnalysis.py)\n"
  },
  {
    "path": "Uber/README.md",
    "content": "## Questions on SQL:  \n\n1. Let's say there is a table called Completed_Trips. The fields present in the table are `rider_id`,`trip_id` and `trip_date`.Assume there are `X` riders in week 1 and Y riders in immediate following week 2. Retention is defined as ratio of common riders between `X` and `Y` who took atleast 1 trip and number of riders in week 1 who took atleast 1 trip i.e `X`\n\n**Output:** Plot the retentions for last n weeks -> n is an input here.  \n**Solution:**  \n```\n#n = number of weeks\n\nn = int(input()) #n = 4 or 5 or .....\n\ni = 0\n\nj = 1\n\n#Assume df is the parent data frame which is completed_trips\n\nretentions = []\n\n#we can use datetime module to compare dates.\n\nwhile (i <= n-1 and j <= n):\n\n    df1 = df[df['trip_date'] < curr_date - 7*i and df['trip_date'] > curr_date - 7*j]\n\n    df2 = df[df['trip_date'] < curr_date - 7*(i+1) and df['trip_date'] > curr_date - 7*(j+1)]\n\n    df1 = df1[df1['trip_id'].notnull()]\n\n    df2 = df2[df2['trip_id'].notnull()]\n\n    count_df1 = set(df1['rider_id'].values) #set gives distinct values\n\n    count_df2 = set(df2['rider_id'].values)\n    \n    numerator = len(count_df1 & count_df2) #gives the common riders among all riders\n\n    denominator = len(count_df2)\n\n    retentions.append(numerator/denominator)\n\n    i += 1\n\n    j += 1\n\n   \n#If n = 4\n#0<=3 and 1<=4\n\n#1<=3 and 2<=4\n\n#2<=3 and 3<=4\n\n#3<=3 and 4<=4 ----------> total 4 times the loop will repeat so we get 4 retentions.\n\nweeks_var = [\"week\" + \"-\" + str(i) for i in range(1,5)]\n\nfinal_data = pd.DataFrame({\"Week\":weeks_var,\"Retention\":retentions},\n                          columns = ['Week','Retention'])\n                          \n#final_data is ready - we can do line charts, trend charts etc in it.\n\n```\n\n## Logical Question (Managerial):  \n  \n2. What are the 3 important metrics that you consider to be important to evaluate people who are reporting to you and why?  \n   + Correctness of Solution Deivered'\n   + Quality of Solution Delivered\n   + Adaptability of Solutions Delivered.  \nYou can form your own answers here.  \n\n\n## Process Flow Question (Architecture):  \n  \n3. What are the steps involved in the process doing the FTP for file of any format and putting it in hive location.  \n   + Step-1: Check the location and access  \n   + Step-2: Check the format of file as hive only supports csv/delimited files.  \n   + Step-3: if it is not csv or delimited then try to convert it into structured data set.  \n   + Step-4: Transfer the file using scp protocol binding in python (pysftp) or linux shell.  \n   + Step-5: Once the file is in respective folder, create a hive table with location inserted in table definition with csv serializer.  \n\n\n"
  },
  {
    "path": "Uber/getNewArray.py",
    "content": "\"\"\"\nGiven an array of integers, return a new array such that each element at index i \nof the new array is the product of all the numbers in the original array except \nthe one at i.\n\nFor example, if our input was [1, 2, 3, 4, 5], the expected output would be \n[120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be \n[2, 3, 6].\n\"\"\"\n\ndef productOfArray(arr):\n    prod = 1\n    for a in arr:\n        prod = prod * a\n    return prod\n\ndef newArray(arr):\n    n = len(arr)\n    new_arr = [None]*n\n    for i in range(n):\n        item = arr.pop(i)\n        x = productOfArray(arr)\n        new_arr[i] = x\n        arr.insert(i,item)\n    return new_arr\n    \nif __name__ == '__main__':\n    T = int(input())\n    for tcs in range(T):\n        arr = list(map(int,input().strip().split()))\n        print (newArray(arr))"
  },
  {
    "path": "Ushur/README.md",
    "content": "# Personal Experience:  \n## First round - Hackerearth Test 2021 (Data Analytics Engineer):  \n+ Fairly simple coding question (added above) and more multiple choice questions on Machine learning (More than one option, single option etc).  \n"
  },
  {
    "path": "Ushur/findPairs.py",
    "content": "\"\"\"\nGiven a list of numbers and each number represents a different color of\na sock, Find the number of pairs that can be formed from given list of\nsocks\n\n\"\"\"\n\nimport collections\ndef find_pairs(n,socks):\n    num_pairs = 0\n    freqs = collections.Counter(socks)\n    for s,c in freqs.items():\n        if c >= 2:\n            num_pairs += (c//2)\n    return num_pairs\n\n\nif __name__ == '__main__':\n    N = 9\n    socks = [1,2,2,1,3,4,5,2,2]\n    print (find_pairs(N, socks))\n    \n    N = 10\n    socks = [1,1,2,1,3,4,5,2,2,0]\n    print (find_pairs(N, socks))"
  },
  {
    "path": "VMWare/Convert_Infix_To_Postfix.py",
    "content": "{\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n# This code is contributed by Nikhil Kumar Singh(nickzuck_007)\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\nif __name__ == '__main__':\n    test_cases = int(input())\n    for cases in range(test_cases) :\n        exp = str(input())\n        print(InfixtoPostfix(exp))\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\nFunction Arguments :\n\t\t@param  : exp (given infix expression)\n\t\t@return : string\n'''\ndef InfixtoPostfix(exp):\n    #code here\n    import string\n    stack = []\n    prec = {'^':4,'*':3,'/':3,'+':2,'-':2,'(':1}\n    postfixexp = []\n    tokens = list(exp)\n    for token in tokens:\n        if ((token in string.ascii_lowercase) | (token in \"0123456789\") | (token in string.ascii_uppercase)):\n            postfixexp.append(token)\n        elif token == '(':\n            stack.append(token)\n        elif token == ')':\n            if len(stack)!=0:\n                topToken = stack.pop()\n                while topToken != '(':\n                    postfixexp.append(topToken)\n                    topToken = stack.pop()\n        else:\n            if len(stack) != 0:\n                while (len(stack)!=0) and (prec[stack[-1]] >= prec[token]):\n                    postfixexp.append(stack.pop())\n            stack.append(token)\n    while len(stack)!=0:\n        postfixexp.append(stack.pop())\n    return \"\".join(postfixexp)"
  },
  {
    "path": "VMWare/maxIndexDiffOfArray.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            n=int(input())\n            \n            arr=[int(x) for x in input().strip().split()]\n            print(maxIndexDiff(arr,n))\n            \n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n#Complete this function\ndef maxIndexDiff(arr, n): \n    ##Your code here\n    maxxDiff = 0\n    for i in range(n):\n        for j in range(i+1,n):\n            if arr[i]<=arr[j]:\n                if maxxDiff < j - i:\n                    maxxDiff = j - i\n    return maxxDiff"
  },
  {
    "path": "VMWare/mergeKSortedLinkedLists.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n# prints the elements of linked list starting with head\ndef printList(head):\n    if head is None:\n        print(' ')\n        return\n    curr_node = head\n    while curr_node:\n        print(curr_node.data,end=\" \")\n        curr_node=curr_node.next\n    print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n = int(input())\n        a= []\n        for i in range(n):\n            a.append(LinkedList())\n        list_info = list(map(int,input().strip().split()))\n        curr_ind = 0\n        curr_list_ind = 0\n        while curr_ind < len(list_info):\n            nodes= list_info[curr_ind]\n            curr_ind+=1\n            for i in range(nodes):\n                a[curr_list_ind].append(list_info[curr_ind])\n                curr_ind += 1\n            curr_list_ind += 1\n        heads = []\n        for i in range(n):\n            heads.append(a[i].head)\n        printList(merge(heads,n))\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to merge the given k sorted\n\tlinked lists into one list and return\n\tthe head of the new formed linked list.\n\t\n\tFunction Arguments: array \"heads\" (containing heads of linked lists), n size of array a.\n\tReturn Type: head node.;\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n'''\ndef merge(heads,n):\n    #code here\n    newll = LinkedList()\n    new_list = []\n    for h in heads:\n        curr_node = h\n        while curr_node != None:\n            new_list.append(curr_node.data)\n            curr_node = curr_node.next\n    new_list = sorted(new_list)\n    for ele in new_list:\n        newll.append(ele)\n    return newll.head"
  },
  {
    "path": "Vimeo/README.md",
    "content": "# Senior Data Engineer: Interview Process For Vimeo - 2024:  \n## First Round (Format):  \n+ Coding Test with Interviewers present to observe, on Qualified Platform (https://www.qualified.io/).\n+ SQL section (5 Questions) and Python section (5 Questions), 25 minutes for each section. There is a hard stop when 25 mins is over for each section.  \n+ Python programming section covers questions from Arrays, Linkedlists and Trees and Tree Traversals (Medium Level).\n+ SQL questions involve Advanced SELECT and JOINS.\n\nQuestions are subject to change with each test, but the format is likely to remain same, but who knows? :blush: :grin:  \n"
  },
  {
    "path": "Visa/addNode_DoublyLinkedList.py",
    "content": "{\nclass Node:\n\tdef __init__(self, data):\n\t\tself.data = data\n\t\tself.next = None\n\t\tself.prev = None\nclass DoublyLinkedList:\n\tdef __init__(self):\n\t\tself.head = None\n\tdef append(self, new_data):\n\t\tnew_node = Node(new_data)\n\t\tnew_node.next = None\n\t\tif self.head is None:\n\t\t\tnew_node.prev = None\n\t\t\tself.head = new_node\n\t\t\treturn\n\t\tlast = self.head\n\t\twhile(last.next is not None):\n\t\t\tlast = last.next\n\t\tlast.next = new_node\n\t\tnew_node.prev = last\n\t\treturn\n\tdef printList(self, node):\n\t\twhile(node.next is not None):\n\t\t\tnode = node.next\n\t\twhile node.prev is not None:\n\t\t    node = node.prev\n\t\twhile(node is not None):\n\t\t    print(node.data, end=\" \")\n\t\t    node = node.next\n\t\tprint()\n\t\t\nif __name__=='__main__':\n    t = int(input())\n    for i in range(t):\n        n = int(input())\n        arr = map(int, input().strip().split())\n        llist = DoublyLinkedList()\n        for e in arr:\n            llist.append(e)\n        pos,data = map(int, input().strip().split())\n        addNode(llist.head, pos, data)\n        llist.printList(llist.head)\n# Contributed by: Harshit Sidhwa\n\n}\n''' This is a function problem.You only need to complete the function given below '''\n# Your task is to complete this function\n# function should add a new node after the pth position\n# function shouldn't print or return any data\n'''\nclass Node:\n\tdef __init__(self, data):\n\t\tself.data = data\n\t\tself.next = None\n\t\tself.prev = None\n'''\ndef addNode(head, p, data):\n    # Code here\n    temp = Node(data)\n    if head == None:\n        head = temp\n        return\n    curr_node = head\n    C = 0\n    while C <= p:\n        if C == p:\n            temp.next = curr_node.next\n            curr_node.next = temp\n            if temp.next is not None:\n                temp.next.prev = temp\n            temp.prev = curr_node\n        curr_node = curr_node.next\n        C += 1\n    return"
  },
  {
    "path": "Visa/populateList.py",
    "content": "\"\"\"\nPopulate the list according to following fashion\n\nGiven a list of elements [a0, a1, a2, ......, an-1] of length n\n\nReturn a list of length n such that it has the following traversal\n\nInput: [a0, a1, a2, ......, an-1]\nOutput: [a0, an-1, a1, an-2, a2, an-3,........]\n\"\"\"\n\ndef solution(numbers):\n    size_of_arr = len(numbers)\n    result = list()\n    for ind in range(size_of_arr):\n        if len(result) == size_of_arr:\n            break\n        result.append(numbers[ind])\n        if (ind != size_of_arr - ind - 1):\n            result.append(numbers[size_of_arr - ind - 1])\n    return result\n\nif __name__ == '__main__':\n    input1 = [2, 5, -10, -4, 0, 8]\n    print (solution(input1))\n\n    input2 = [1, 20, 3, 8, 5]\n    print (solution(input2))\n\n    input3 = [10, -1, 0, 8, 9, -1, 5, -5, 6, 9, 20, 10]\n    print (solution(input3))"
  },
  {
    "path": "Visa/removeDuplicatesSortedLinkedList.py",
    "content": "{\n#Initial Template for Python 3\n#Contributed by : Nagendra Jha\nimport atexit\nimport io\nimport sys\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n@atexit.register\ndef write():\n    sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n    \n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\n    \nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n = int(input())\n        a = LinkedList() # create a new linked list 'a'.\n        nodes = list(map(int, input().strip().split()))\n        for x in nodes:\n            a.append(x)\n        removeDuplicates(a.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tYour task is to remove duplicates from given \n\tsorted linked list.\n\t\n\tFunction Arguments: head (head of the given linked list) \n\tReturn Type: none, just remove the duplicates from the list.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n'''\ndef removeDuplicates(head):\n    #code here\n    global a\n    curr_node = head\n    duplicateTracker = []\n    while curr_node != None:\n        if curr_node.data not in duplicateTracker:\n            duplicateTracker.append(curr_node.data)\n        curr_node = curr_node.next\n    a = LinkedList()\n    for x in duplicateTracker:\n        a.append(x)"
  },
  {
    "path": "Walmart/GroupAnagrams.py",
    "content": "## Data Engineering Interview at Walmart\n\n# Find the words from the given list and group them with the words which are \n# formed by different arrangements of the same letters(anagram)\n\n# Input = ['mat','tam','cute','beat','eatb','teab','ateb']\n# Output = [[“mat”, “tam”],[“cute”],[“beat”,”eatb”,”teab”,”ateb”]]\n\n# Input = ['lump', 'eat',  'me',  'tea', 'em', 'plum']\n\n# Without using Advanced Data structures and libraries\nfrom typing import List,Tuple\nfrom collections import defaultdict\ndef group_anagrams(words:List[str]) -> List[Tuple[str]]:\n    groups = []\n    for i in range(len(words)):\n        collect_groups=[]\n        for j in range(i+1,len(words)):\n            if sorted(words[i]) == sorted(words[j]):\n                if words[i] != words[j]:\n                    collect_groups.append(words[i])\n                    collect_groups.append(words[j])\n                else:\n                    continue\n        if len(collect_groups) > 0:\n            groups.append(tuple(set(collect_groups)))\n        else:\n            groups.append((words[i],))\n    result = []\n    for i in range(len(groups)):\n        checker = []\n        for j in range(len(groups)):\n            if i != j:\n                if set(groups[i]).issubset(set(groups[j])):\n                    checker.append(1)\n                else:\n                    checker.append(0)\n            else:\n                continue\n        if (len(set(checker)) == 1) and (0 in checker):\n            result.append(groups[i])\n    return result\n\ndef group_anagrams_1(words:List[str]) -> List[Tuple[str]]:\n    temp = defaultdict(list)\n    for ele in words:\n        temp[str(sorted(ele))].append(ele)\n    print (temp)\n    return list(temp.values())\n\nif __name__ == '__main__':\n    # words = list(input().strip().split(\",\"))\n    # print (group_anagrams(words=words))\n    print (group_anagrams_1(words=['lump', 'eat',  'me',  'tea', 'em', 'plum']))\n    print (group_anagrams(words=['mat','tam','cute','beat','eatb','teab','ateb']))\n    print (group_anagrams_1(words=['mat','tam','cute','beat','eatb','teab','ateb']))"
  },
  {
    "path": "Walmart/minimumCoins.py",
    "content": "# Given a value V, if we want to make a change for V cents, and we have a finite supply of \n# each of C = { C1, C2, .., Cm} valued coins, what is the minimum number of coins to make the change? \n# If it’s not possible to make a change, print -1.\n\n# Examples:  \n# finite supply is just coin values provided in the list, cannot use more than those\n\n# Input: coins[] = {25, 10, 5}, V = 30\n# Output: Minimum 2 coins required We can use one coin of 25 cents and one of 5 cents \n\n# Input: coins[] = {9, 6, 5, 1}, V = 11\n# Output: Minimum 2 coins required We can use one coin of 6 cents and 1 coin of 5 cents\n\nfrom typing import List\nimport itertools\ndef minCoins(coins:List[int],value:int) -> int:\n    if value == 0:\n        return 0\n    maxlength = len(coins)\n    for l in range(1,maxlength,1):\n        combinations = list(itertools.combinations(coins,l))\n        for c in combinations:\n            if sum(c)==value:\n                return f\"Minimum {l} coins required, we can use coins of {(','.join([str(i) for i in c]))} cents\"\n            else:\n                continue\n    return -1\n\n\nif __name__ == '__main__':\n    coins = list(map(int,input().strip().split(' ')))\n    value = int(input())\n    print (minCoins(coins,value))"
  },
  {
    "path": "Walmart/minimumCoinsRecursive.py",
    "content": "# Given a value V, if we want to make a change for V cents, and we have an infinite supply of \n# each of C = { C1, C2, .., Cm} valued coins, what is the minimum number of coins to make the change? \n# If it’s not possible to make a change, print -1.\n\n# Examples:  \n\n# Input: coins[] = {25, 10, 5}, V = 30\n# Output: Minimum 2 coins required We can use one coin of 25 cents and one of 5 cents \n\n# Input: coins[] = {9, 6, 5, 1}, V = 11\n# Output: Minimum 2 coins required We can use one coin of 6 cents and 1 coin of 5 cents\n\nfrom typing import List\nimport sys\ndef minimumCoinsRecursive(coins:List[int],value:int) -> int:\n    if value == 0:\n        return 0\n    coins_l = len(coins)\n    res = sys.maxsize\n    for i in range(coins_l):\n        if coins[i] <= value:\n            sub_res = minimumCoinsRecursive(coins,value-coins[i])\n            if ((sub_res != sys.maxsize) & (sub_res + 1 < res)):\n                res = sub_res + 1\n    return res\n\nif __name__ == '__main__':\n    coins = list(map(int,input().strip().split(' ')))\n    print (coins)\n    value = int(input())\n    print (value)\n    print (minimumCoinsRecursive(coins,value))"
  },
  {
    "path": "Yahoo/ThreeWayPartition.py",
    "content": "{\n# Driver Program\nfrom collections import Counter\nif __name__=='__main__':\n    t = int(input())\n    for i in range(t):\n        n = int(input())\n        arr = list(map(int, input().strip().split()))\n        brr = Counter(arr)\n        a,b = list(map(int, input().strip().split()))\n        res = threeWayPartition(arr, n, a, b)\n        k1 = k2 = k3 = 0\n        for e in arr:\n            if e > a:\n                k3+=1\n            elif e<=a and e>=b:\n                k2+=1\n            elif e<a:\n                k1+=1\n        m1 = m2 = m3 = 0\n        for e in range(k1):\n            if res[e]<a:\n                m1+=1\n        for e in range(k1, k1+k2):\n            if res[e]<=a and res[e]>=b:\n                m2+=1\n        for e in range(k1+k2, k1+k2+k3):\n            if res[e]>=a:\n                m3+=1\n        flag = False\n        if k1==m1 and k2==m2 and k3==m3:\n            flag = True\n        for e in range(len(res)):\n            brr[res[e]]-=1\n        for e in range(len(res)):\n            if brr[res[e]]!=0:\n                flag = False\n        if flag:\n            print(1)\n        else:\n            print(0)\n# Contributed by: Harshit Sidhwa\n}\n''' This is a function problem.You only need to complete the function given below '''\n # Your task is to complete this function\n# function should a list containing the required order of the elements\ndef threeWayPartition(arr, n, a, b):\n    # Code here\n    lessa = []\n    atob = []\n    greatb = []\n    for i in range(n):\n        if arr[i] < a:\n            lessa.append(arr[i])\n        elif arr[i] >= a and arr[i] <= b:\n            atob.append(arr[i])\n        elif arr[i] > b:\n            greatb.append(arr[i])\n    farr = lessa + atob + greatb\n    return farr"
  },
  {
    "path": "ZSAssociates/CrossSequence.py",
    "content": "\"\"\"\nGiven an array A, Integer K\n\nFind the Kth Smallest element of array which is generated from\ncalculating the absolute differences of the cartesian product of the \narray elements\n\n\nExample:\n    A = [4,2,1]\n    K = 5\n    N = size(A) = 3\n    \n    S = [|4-4|,|4-2|,|4-1|,|2-4|,|2-2|,|2-1|,|1-4|,|1-2|,|1-1|]\n    S = [0,2,3,2,0,1,3,1,0]\n    S = [0,0,0,1,1,2,2,3,3,3] (sorted)\n    5th Smallest element (assuming 1-indexing) is 4\n\"\"\"\n\nimport itertools\ndef solve(N,A,K):\n    cartesian_product = itertools.product(A,A)\n    abs_diffs = [abs(i-j) for i,j in cartesian_product]\n    return sorted(abs_diffs)[K-1]\n\nif __name__ == '__main__':\n    A = [4,2,1]\n    N = len(A)\n    K = 5\n    print (solve(N,A,K))"
  },
  {
    "path": "ZSAssociates/OutputOfProgram.py",
    "content": "import pandas as pd\nfrom pyspark import SparkContext\nfrom pyspark.sql.functions import col,struct,pandas_udf,PandasUDFType\nfrom pyspark.sql import SQLContext\nsc = SparkContext(\"local\",\"test\")\nx = pd.Series([1,2,3])\npdf = pd.DataFrame([1,2,3],columns = ['x'])\ndf = SQLContext(sc).createDataFrame(pdf)\n\n@pandas_udf(\"long\",PandasUDFType.SCALAR_ITER)\ndef plus_one(batch_iter):\n    for x in batch_iter:\n        yield x + 1\n        \n@pandas_udf(\"long\",PandasUDFType.SCALAR_ITER)\ndef multiply_two_cols(batch_iter):\n    for a,b in batch_iter:\n        yield a * b\n        \ndf.select(multiply_two_cols(col(\"x\"),col(\"x\"))).show()"
  },
  {
    "path": "ZSAssociates/OutputOfProgram2.py",
    "content": "def MainProgram(iterable, x):\n    sample = tuple(iterable)\n    n = len(sample)\n    if not n and x:\n        return\n    indices = [1] * x\n    yield tuple(sample[i] for i in indices)\n    while True:\n        for i in reversed(range(x)):\n            if indices[i] != n-1:\n                break\n            else:\n                return\n        indices[i:] = [indices[i] + 1] * (x-i)\n        yield tuple(sample[i] for i in indices)\n\na = MainProgram('PYTHON', 3)\nprint (next(a))\n\ndef MainProg(f):\n    m = {}\n    def InnerProg(num):\n        if num not in m:\n            m[num] = f(num)\n        return m[num]\n    return InnerProg\n\n@MainProg\ndef Call(num):\n    if num == 0:\n        return 1\n    else:\n        return num**2*Call(num-1)\n    \nprint (Call(3))"
  },
  {
    "path": "Zoho/merge2SortedLinkedLists.py",
    "content": "{\n#Initial Template for Python 3\n# Node Class\nclass Node:\n    def __init__(self, data):   # data -> value stored in node\n        self.data = data\n        self.next = None\n# Linked List Class\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n    # creates a new node with given value and appends it at the end of the linked list\n    def append(self, new_value):\n        new_node = Node(new_value)\n        if self.head is None:\n            self.head = new_node\n            return\n        curr_node = self.head\n        while curr_node.next is not None:\n            curr_node = curr_node.next\n        curr_node.next = new_node\n    # prints the elements of linked list starting with head\n    def printList(self):\n        if self.head is None:\n            print(' ')\n            return\n        curr_node = self.head\n        while curr_node:\n            print(curr_node.data,end=\" \")\n            curr_node=curr_node.next\n        print(' ')\nif __name__ == '__main__':\n    t=int(input())\n    for cases in range(t):\n        n,m = map(int, input().strip().split())\n        a = LinkedList() # create a new linked list 'a'.\n        b = LinkedList() # create a new linked list 'b'.\n        nodes_a = list(map(int, input().strip().split()))\n        nodes_b = list(map(int, input().strip().split()))\n        for x in nodes_a:\n            a.append(x)\n        for x in nodes_b:\n            b.append(x)\n        a.head = merge(a.head,b.head)\n        a.printList()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n'''\n\tFunction to merge two sorted lists in one\n\tusing constant space.\n\t\n\tFunction Arguments: head_a and head_b (head reference of both the sorted lists)\n\tReturn Type: head of the obtained list after merger.\n\t{\n\t\t# Node Class\n\t\tclass Node:\n\t\t    def __init__(self, data):   # data -> value stored in node\n\t\t        self.data = data\n\t\t        self.next = None\n\t}\n\tContributed By: Nagendra Jha\n'''\ndef merge(head_a,head_b):\n    #code here\n    global a\n    elements = []\n    curr_node = head_a\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    curr_node = head_b\n    while curr_node != None:\n        elements.append(curr_node.data)\n        curr_node = curr_node.next\n    elements = sorted(elements)\n    a = LinkedList()\n    for i in elements:\n        a.append(i)\n    return a.head"
  },
  {
    "path": "Zoho/rearrangeArrayAlternately.py",
    "content": "{\n#Initial Template for Python 3\nimport math\ndef main():\n        T=int(input())\n        while(T>0):\n            \n            n=int(input())\n            \n            arr=[int(x) for x in input().strip().split()]\n            \n            arre = rearrange(arr,n)\n            \n            for i in arre:\n                print(i,end=\" \")\n            \n            print()\n            \n            T-=1\nif __name__ == \"__main__\":\n    main()\n}\n''' This is a function problem.You only need to complete the function given below '''\n#User function Template for python3\n##Complete this function\ndef rearrange(arr, n): \n    ##Your code here\n    if n%2 == 0:\n        for i in range(n//2):\n            arr.append(arr[n-1-i])\n            arr.append(arr[i])\n    else:\n        for i in range(n//2):\n            arr.append(arr[n-1-i])\n            arr.append(arr[i])\n        arr.append(arr[math.floor(n/2)])\n    arr[:] = arr[n:]\n    return arr"
  },
  {
    "path": "Zycus/README.md",
    "content": "# Personal Experience (Interview Process for AI/Machine Learning Engineer - 2020):  \n### First screening round:  \n+ Interview with the Director of AI teams:  \n\nCase study: Dataset is as below:  \n  \n| itemId | item_name | item_description      | manufacturer_name | supplier_name | target_variable(home/workplace) |\n|--------|-----------|-----------------------|-------------------|---------------|---------------------------------|\n| 1000   | monitor   | ram: 32gb,2.8 GHZ,HDD | HP                | senty pvt ltd | workplace                       |\n| 1001   |           |                       |                   |               |                                 |\n| 1003   |           |                       |                   |               |                                 |  \n\nGiven only sample size of 10 of above schema (with target variable assigned), training dataset(without target_variable assigned) size is 100, how would you avoid the effort of manual tagging  of target variable to training data?  \n#### Follow up questions:  \n+ How would you select the variables?\n+ How would u use the opentext column `item_description`?\n\nThe round is for just 10 minutes, and I didn't get selected.\n\n#### My solution:  \n+ k-NN/decision tree algorithm for dependent variable tagging (even associaton rule mining algorithms that include apriori and eclat).  \n+ initial selection of variables is based on domain knowledge as number of variables is very less here.\n+ preprocess the text column `item_description` maybe do text summarization of the full text and extract keywords using bi-grams and collocations and use that tag in further processing.  \n\n\n## Use https://www.tablesgenerator.com/markdown_tables# for quick tables generation in markdown, It's elegant and simple.  \n"
  },
  {
    "path": "cimpress/README.md",
    "content": "Interview Process for Data Engineer - 2021 (Personal Experience):  \n=================================================================\n### 1. First Round - Introductory Round:  \n+ Introduction to yourself,About the company.  \n+ Project experience, Tech stacks you are comfortable with, basic programming questions.  \n+ Relevance of your background to the role.  \n+ Interview process detailing and other questions if you may have or interviewer has.  \n\n### 2. Online Coding Test on Codility:  \n+ 1 question on SQL and 1 question on programming.  \n+ Programming question - Say a string composed of only letters a and b, numbers of ways to split it into 3 substrings such that all 3 substrings have same number of character 'a's.  \n+ SQL question:  Please find the question below -  \n  \n  ![image](https://user-images.githubusercontent.com/25507554/120599363-0a640480-c465-11eb-8b40-bb91a3c8bc3c.png)\n  \n### 3. Coding Round (Programming test - Data transformations using Apache Spark Live):  \n+ Given 2 data questions - Transform data using Apache spark transformations live, Execute them and present the results - environment for execution of spark programs is provided.  \n  \n### 4. Design Round:  \n+ Document is provided which describes the problem statement and bottlenecks in existing architecture and what the requirement is - Design a scalable Machine learning system that automates the e2e ML workflows and helps analysts and stakeholders in their seamless outputs consumption - Architectural choices, Technology stack that you choose need to be explained clearly and reason behind that choice - would be an addition if the alternative approaches are also explained.  \n  \n### 5. Problem Solving Round:  \n+ This round is not a technical interview but tests on the problem solving skills of yours - A real world situation with some helpers are given, come up with the steps to mitigate the problem and measures taken to solve that problem.  \n\n### 6. Awesomeness interview:  \n+ Discussions and questions about working with a team and challenges that are faced - questions on how you handled that in past.  \n\n### 7. Behavioral Interview:  \n+ Working under a stressful situation.  \n+ How is the conflict with a co-worker resolved?  \n+ How do you keep yourself updated and enthusiastic about latest tech trends? and other questions.  \n"
  }
]