├── LeetCodePractice ├── My_trie.py ├── 664. Strange Printer.py ├── Add to List 270. Closest Binary Search Tree Value.py ├── 120. Triangle.py ├── 719. Find K-th Smallest Pair Distance.py ├── Reorder List.py ├── 645. Set Mismatch.py ├── 721. Accounts Merge.py ├── Median of Two Sorted Arrays.py ├── 287. Find the Duplicate Number.py ├── 274. H-Index.py ├── 461. Hamming Distance.py ├── Remove Duplicate Letters.py ├── 657. Judge Route Circle.py ├── Excel Sheet Column Number.py ├── Remove Duplicates from Sorted Array.py ├── 651. 4 Keys Keyboard.py ├── 100. Same Tree.py ├── 238. Product of Array Except Self.py ├── 452. Minimum Number of Arrows to Burst Balloons.py ├── 301. Remove Invalid Parentheses.py ├── 643. Maximum Average Subarray I.py ├── 805. Split Array With Same Average.py ├── Contains Duplicate II.py ├── Same Tree.py ├── Single Element in a Sorted Array.py ├── 22. Generate Parentheses.py ├── 121. Best Time to Buy and Sell Stock.py ├── 451. Sort Characters By Frequency.py ├── 560. Subarray Sum Equals K.py ├── 386. Lexicographical Numbers.py ├── 91. Decode Ways.py ├── 50. Pow(x, n).py ├── 670. Maximum Swap.py ├── Count Complete Tree Nodes.py ├── 654. Maximum Binary Tree.py ├── 565. Array Nesting.py ├── 693. Binary Number with Alternating Bits.py ├── 42. Trapping Rain Water.py ├── Search a 2D Matrix II.py ├── 673. Number of Longest Increasing Subsequence.py ├── 98. Validate Binary Search Tree.py ├── Contains Duplicate.py ├── Group Anagrams.py ├── 442. Find All Duplicates in an Array.py ├── 387. First Unique Character in a String.py ├── 11. Container With Most Water.py ├── 676. Implement Magic Dictionary.py ├── 682. Baseball Game.py ├── 167. Two Sum II - Input array is sorted.py ├── LONGEST CONSECUTIVE SEQUENCE.py ├── 266. Palindrome Permutation.py ├── 734. Sentence Similarity.py ├── Two Sum.py ├── 270. Closest Binary Search Tree Value.py ├── Missing Number.py ├── 544. Output Contest Matches.py ├── 720. Longest Word in Dictionary.py ├── 155. Min Stack.py ├── 680. Valid Palindrome II.py ├── First Bad Version.py ├── 513. Find Bottom Left Tree Value.py ├── Find All Anagrams in a String.py ├── Remove K Digits.py ├── 563. Binary Tree Tilt.py ├── 563.Binary Tree Tilt.py ├── 366. Find Leaves of Binary Tree.py ├── Remove Duplicates from Sorted Array II.py ├── 661. Image Smoother.py ├── 230. Kth Smallest Element in a BST.py ├── 62. Unique Paths.py ├── 283. Move Zeroes.py ├── 644. Maximum Average Subarray II.py ├── Longest Palindromic Substring.py ├── Find the Duplicate Number.py ├── 19. Remove Nth Node From End of List.py ├── 572. Subtree of Another Tree.py ├── 671. Second Minimum Node In a Binary Tree.py ├── 161. One Edit Distance.py ├── 219. Contains Duplicate II.py ├── Longest Common Prefix.py ├── 582. Kill Process.py └── Find All Numbers Disappeared in an Array.py ├── GeneralPractice ├── Unity1.py ├── 394. Decode String.py ├── 1648. Sell Diminishing-Valued Colored Balls.py ├── MainClassHelper.pyc ├── Minimum Swaps to bring elements together.py ├── ParseJSON.py ├── MainClassHelper.py ├── Addition of arrays.py ├── 1743. Restore the Array From Adjacent Pairs.py ├── 743. Network Delay Time.py ├── BFS and DFS │ ├── 1643. Kth Smallest Instructions.py │ ├── 1557. Minimum Number of Vertices to Reach All Nodes.py │ ├── 797. All Paths From Source to Target.py │ ├── PrintAllPathsInMatrix.py │ └── 133. Clone Graph.py ├── 123456789.py ├── CS353_latex.py ├── MainClassTest.py ├── KeyBoardException.py ├── PoolExample.py ├── 1525. Number of Good Ways to Split a String.py ├── SortTuples.py ├── HighOrderFunctions.py ├── ConceptOfFreeVariable.py ├── max events can be attended.py ├── MainClass.py ├── 279. Perfect Squares.py ├── 1389. Create Target Array in the Given Order.py ├── 1408. String Matching in an Array.py ├── 617. Merge Two Binary Trees.py ├── 1614. Maximum Nesting Depth of the Parentheses.py ├── Google Monarchy.py ├── 162. Find Peak Element.py ├── 621. Task Scheduler.py ├── Temp.py ├── 937. Reorder Data in Log Files.py ├── 31. Next Permutation.py ├── Palindrome subsequence.py ├── 804. Unique Morse Code Words.py ├── 15. 3Sum.py ├── 41. First Missing Positive.py ├── Football_score.py ├── 680. Valid Palindrome II.py ├── 5561. Get Maximum in Generated Array.py ├── contact_dedup.py ├── 1047. Remove All Adjacent Duplicates In String.py ├── 973. K Closest Points to Origin.py ├── 1750. Minimum Length of String After Deleting Similar Ends.py ├── TopologicalSort_Method1.py ├── 739. Daily Temperatures.py ├── 282. Expression Add Operators.py ├── 752. Open the Lock.py ├── 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.py ├── 1631. Path With Minimum Effort.py ├── 1578. Minimum Deletion Cost to Avoid Repeating Letters.py ├── Sum of k smallest elements in BST.py ├── 1606. Find Servers That Handled Most Number of Requests.py ├── 3 Minimas.py ├── 538. Convert BST to Greater Tree.py ├── 124. Binary Tree Maximum Path Sum.py ├── 1626. Best Team With No Conflicts.py ├── LinkedIn Rever Depth Sum.py ├── MergeSort.py ├── 684. Redundant Connection.py ├── 838. Push Dominoes.py └── 1282. Group the People Given the Group Size They Belong To.py ├── Internships ├── Twitter │ ├── SecondQs.py │ └── __init__.py ├── Bloomberg │ ├── 4312.pdf │ ├── 4313.pdf │ ├── 4314.pdf │ ├── 4315.pdf │ ├── 4316.pdf │ ├── 4317.pdf │ ├── 4318.pdf │ ├── 4319.pdf │ ├── __init__.py │ └── License to Hack.py ├── Aetion │ ├── __init__.py │ └── ArithmeticSequence.py ├── Veritas │ ├── Array Reduction │ └── Rolling Stirng.py ├── Kabam │ └── ElectionWinner.py ├── NextCapital │ ├── Character Multiple.py │ ├── ArrayProcessor.py │ └── 2D Lake.py ├── Formlabs_serverCode.py ├── LiveRamp │ ├── Monkey.py │ └── BFS.py ├── Delete and Earn - VMWARE.py └── Google │ └── StringManipulation.py ├── AlphaBeta ├── Tic Tac toe │ ├── TTT_input.txt │ ├── Random_User.png │ ├── CTO_HackerEarth.png │ └── README.md ├── PrunedTree.png ├── Example_Used.png ├── BattleOfBots1 │ └── isola_input.txt └── README.md ├── CompaniesHiringQuestions ├── purestorag.py ├── input.txt ├── Aditifriend2.py ├── nutanix2.py ├── List_Mutability.py ├── Twitter4.py ├── MicrosoftCoding_TowerOfHanaoi.py ├── Balance Point.py ├── amazon1.py ├── Zappos_1.21 Gigawatts.py ├── Microsoft_3 numbers with even occurence.py ├── Twitter2.py ├── Bloomberg.py ├── Expedia2.py ├── MicrosoftCoding_Order.py ├── MicrosoftCoding_SecretDecoder.py ├── Zappos_FormMinNumber.py ├── Twitter1.py ├── Expedia1.py ├── 1658. Minimum Operations to Reduce X to Zero.py ├── Stripe2020.py └── AditiFriend1.py ├── .idea ├── .gitignore ├── vcs.xml ├── inspectionProfiles │ └── profiles_settings.xml ├── misc.xml ├── modules.xml └── CompetitiveProgramming.iml ├── MainClassHelper.pyc ├── serverlessPrograms ├── .npmignore └── .serverless │ ├── aws-nodejs.zip │ └── cloudformation-template-create-stack.json ├── MainClassHelper.py ├── HackerRankProblems ├── Flipping bits.py ├── ASCII Flower.py ├── Highlight Landmarks.py ├── LeftRotate.py ├── Counting Binary Substrings.py ├── Birthday Chocolate.py ├── Balanced Subsequence.py ├── Jim and the Skyscrapers.py ├── Emails, emails everywhere!.py └── Balanced Brackets.py ├── Leetcode_Challenge ├── Aug 27 │ ├── Find the Difference.py │ └── Elimination Game.py ├── Sep 17 │ └── Frog Jump.py ├── Sep 24 │ ├── Convert a Number to Hexadecimal.py │ └── Left Leaves Sum.py ├── Feb 18 │ └── Detect Capital.py ├── Oct 8 │ └── Partition Equal Subset Sum.py ├── Oct 15 │ ├── Longest Repeating Character Replacement.py │ └── Valid Word Square.py └── Oct 1 │ └── Longest Palindrome.py ├── CS353_latex.py ├── MainClassTest.py ├── MainClass.py ├── DL_Safari.py ├── NewLeetCodeProblems └── 1017. Convert to Base -2.py ├── Group People.py ├── Codility.py └── Zookeeper └── basics_kazoo.py /LeetCodePractice/My_trie.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /GeneralPractice/Unity1.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | -------------------------------------------------------------------------------- /Internships/Twitter/SecondQs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Expression S/R 3 | """ -------------------------------------------------------------------------------- /AlphaBeta/Tic Tac toe/TTT_input.txt: -------------------------------------------------------------------------------- 1 | 1 0 0 2 | 0 0 0 3 | 0 0 0 4 | 2 -------------------------------------------------------------------------------- /CompaniesHiringQuestions/purestorag.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | -------------------------------------------------------------------------------- /GeneralPractice/394. Decode String.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | -------------------------------------------------------------------------------- /LeetCodePractice/664. Strange Printer.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /GeneralPractice/1648. Sell Diminishing-Valued Colored Balls.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | -------------------------------------------------------------------------------- /LeetCodePractice/Add to List 270. Closest Binary Search Tree Value.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | -------------------------------------------------------------------------------- /MainClassHelper.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/MainClassHelper.pyc -------------------------------------------------------------------------------- /AlphaBeta/PrunedTree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/AlphaBeta/PrunedTree.png -------------------------------------------------------------------------------- /AlphaBeta/Example_Used.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/AlphaBeta/Example_Used.png -------------------------------------------------------------------------------- /Internships/Bloomberg/4312.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/Internships/Bloomberg/4312.pdf -------------------------------------------------------------------------------- /Internships/Bloomberg/4313.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/Internships/Bloomberg/4313.pdf -------------------------------------------------------------------------------- /Internships/Bloomberg/4314.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/Internships/Bloomberg/4314.pdf -------------------------------------------------------------------------------- /Internships/Bloomberg/4315.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/Internships/Bloomberg/4315.pdf -------------------------------------------------------------------------------- /Internships/Bloomberg/4316.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/Internships/Bloomberg/4316.pdf -------------------------------------------------------------------------------- /Internships/Bloomberg/4317.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/Internships/Bloomberg/4317.pdf -------------------------------------------------------------------------------- /Internships/Bloomberg/4318.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/Internships/Bloomberg/4318.pdf -------------------------------------------------------------------------------- /Internships/Bloomberg/4319.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/Internships/Bloomberg/4319.pdf -------------------------------------------------------------------------------- /serverlessPrograms/.npmignore: -------------------------------------------------------------------------------- 1 | # package directories 2 | node_modules 3 | jspm_packages 4 | 5 | # Serverless directories 6 | .serverless -------------------------------------------------------------------------------- /AlphaBeta/Tic Tac toe/Random_User.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/AlphaBeta/Tic Tac toe/Random_User.png -------------------------------------------------------------------------------- /GeneralPractice/MainClassHelper.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/GeneralPractice/MainClassHelper.pyc -------------------------------------------------------------------------------- /AlphaBeta/Tic Tac toe/CTO_HackerEarth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/AlphaBeta/Tic Tac toe/CTO_HackerEarth.png -------------------------------------------------------------------------------- /serverlessPrograms/.serverless/aws-nodejs.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepika087/CompetitiveProgramming/HEAD/serverlessPrograms/.serverless/aws-nodejs.zip -------------------------------------------------------------------------------- /AlphaBeta/BattleOfBots1/isola_input.txt: -------------------------------------------------------------------------------- 1 | 0 0 0 2 0 0 0 2 | 0 0 0 -1 0 0 0 3 | 0 0 0 0 0 0 0 4 | 0 0 0 0 0 0 0 5 | 0 0 0 0 0 0 0 6 | 0 0 0 0 1 0 0 7 | 0 0 0 0 0 0 0 8 | 2 -------------------------------------------------------------------------------- /GeneralPractice/Minimum Swaps to bring elements together.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Minimum swaps required to bring all elements less than or equal to k together 5 | """ -------------------------------------------------------------------------------- /MainClassHelper.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def say_hello(): 5 | return "Hello function" 6 | 7 | 8 | def print_hello(): 9 | return "this is a hello function" 10 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /GeneralPractice/ParseJSON.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution: 5 | 6 | def parse(self, string): 7 | 8 | if len(string) == 0: 9 | return None 10 | 11 | -------------------------------------------------------------------------------- /GeneralPractice/MainClassHelper.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def say_hello(): 5 | return "Hello function" 6 | 7 | 8 | def print_hello(): 9 | return "this is a hello function" 10 | -------------------------------------------------------------------------------- /GeneralPractice/Addition of arrays.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | arr1 = [1, 2, 3, 4, 5] 5 | arr2 = [5, 3, 1, 4] 6 | 7 | sumT = 0 8 | for _ in (arr1 + arr2): 9 | sumT ^= _ 10 | 11 | print sumT -------------------------------------------------------------------------------- /CompaniesHiringQuestions/input.txt: -------------------------------------------------------------------------------- 1 | (02/03/2002-14:00:00) :: START 2 | (02/03/2002-14:00:00) :: CONNECTED 3 | (02/03/2002-14:08:00) :: DISCONNECTED 4 | (02/03/2002-14:10:00) :: CONNECTED 5 | (02/03/2002-14:15:00) :: SHUTDOWN -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /GeneralPractice/1743. Restore the Array From Adjacent Pairs.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def restoreArray(self, adjacentPairs): 6 | """ 7 | :type adjacentPairs: List[List[int]] 8 | :rtype: List[int] 9 | """ 10 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /GeneralPractice/743. Network Delay Time.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def networkDelayTime(self, times, N, K): 6 | """ 7 | :type times: List[List[int]] 8 | :type N: int 9 | :type K: int 10 | :rtype: int 11 | """ 12 | -------------------------------------------------------------------------------- /GeneralPractice/BFS and DFS/1643. Kth Smallest Instructions.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def kthSmallestPath(self, destination, k): 5 | """ 6 | :type destination: List[int] 7 | :type k: int 8 | :rtype: str 9 | """ 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Aditifriend2.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | import json 3 | 4 | 5 | def solution(businesses): 6 | business_count = 0 7 | 8 | parsed_json = json.loads(businesses) 9 | print(parsed_json) 10 | return business_count 11 | 12 | 13 | print(solution 14 | 15 | 16 | 8010211212(input)) -------------------------------------------------------------------------------- /HackerRankProblems/Flipping bits.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import ctypes 4 | 5 | def int32_to_uint32(i): 6 | return ctypes.c_uint32(i).value 7 | 8 | n = int(raw_input()) 9 | 10 | for i in range(0, n): 11 | num = int(raw_input()) 12 | num = int32_to_uint32(num) 13 | print int32_to_uint32(~num) 14 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /GeneralPractice/BFS and DFS/1557. Minimum Number of Vertices to Reach All Nodes.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def findSmallestSetOfVertices(self, n, edges): 6 | """ 7 | :type n: int 8 | :type edges: List[List[int]] 9 | :rtype: List[int] 10 | """ 11 | -------------------------------------------------------------------------------- /CompaniesHiringQuestions/nutanix2.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | arr = [3, 2, 6, 5, 8, 2, 9] 4 | result = [ 0 for i in range(len(arr))] 5 | 6 | for i in range(0, len(arr)): 7 | result[i] = 0 8 | for j in range(i - 1, -1 , -1): 9 | if arr[j] < arr[i]: 10 | result[i] = arr[j] 11 | break 12 | 13 | print(result) 14 | -------------------------------------------------------------------------------- /LeetCodePractice/120. Triangle.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | class Solution(object): 3 | def minimumTotal(self, triangle): 4 | """ 5 | :type triangle: List[List[int]] 6 | :rtype: int 7 | """ 8 | sumT = 0 9 | for _ in triangle: 10 | sumT = sumT + min(_) 11 | return sumT 12 | -------------------------------------------------------------------------------- /Leetcode_Challenge/Aug 27/Find the Difference.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | if __name__=="__main__": 4 | s = raw_input('') 5 | t = raw_input('') 6 | 7 | sList = list(s) 8 | tList = list(t) 9 | for item in sList: 10 | if (item in tList): 11 | tList.remove(item) 12 | #print "Updated t = ", tList 13 | print tList[0] -------------------------------------------------------------------------------- /GeneralPractice/123456789.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def step(s1, i): 5 | if i == 10: 6 | #if eval(s1) == 100: 7 | print s1, " = ", eval(s1) 8 | return 9 | if i != 1: 10 | step(s1 + '+' + str(i), i + 1) 11 | step(s1 + '-' + str(i), i + 1) 12 | step(s1 + str(i), i + 1) 13 | 14 | step('', 1) 15 | 16 | 17 | -------------------------------------------------------------------------------- /Internships/Aetion/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | """ 4 | Find the minimum difference between two elements. 5 | This is wrong becuase if array is -100, -1, 0 6 | My solution will return 99 where as correct answer is 1 7 | """ 8 | def solution(A): 9 | 10 | A = sorted(A) 11 | print A 12 | 13 | if __name__=="__main__": 14 | A = [8, 24, 3, 20, 1, 17] 15 | print solution(A) -------------------------------------------------------------------------------- /CS353_latex.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | target = open('Combined_Exam_without_solutions.tex', 'w+') 5 | ignore = False 6 | for line in open("Combined_Exam.tex"): 7 | if ("begin{solution}" in line): 8 | ignore=True 9 | elif ("end{solution}" in line): 10 | ignore=False 11 | elif (not ignore): 12 | target.write(line) 13 | 14 | print "Done" -------------------------------------------------------------------------------- /Leetcode_Challenge/Sep 17/Frog Jump.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Question was not very clear to me 4 | """ 5 | def canCross(stones): 6 | pos = 0 #since the monkey is always at the 0th position 7 | jumped = 0 8 | for index, value in enumerate(stones): 9 | pass 10 | 11 | 12 | 13 | 14 | if __name__=="__main__": 15 | stones = [0,1,2,3,4,8,9,11] 16 | print canCross(stones) -------------------------------------------------------------------------------- /GeneralPractice/CS353_latex.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | target = open('Combined_Exam_without_solutions.tex', 'w+') 5 | ignore = False 6 | for line in open("Combined_Exam.tex"): 7 | if ("begin{solution}" in line): 8 | ignore=True 9 | elif ("end{solution}" in line): 10 | ignore=False 11 | elif (not ignore): 12 | target.write(line) 13 | 14 | print "Done" -------------------------------------------------------------------------------- /LeetCodePractice/719. Find K-th Smallest Pair Distance.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def smallestDistancePair(self, nums, k): 5 | """ 6 | :type nums: List[int] 7 | :type k: int 8 | :rtype: int 9 | """ 10 | nums = sorted(nums) 11 | 12 | #http://www.geeksforgeeks.org/k-th-smallest-absolute-difference-two-elements-array/ -------------------------------------------------------------------------------- /LeetCodePractice/Reorder List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | class ListNode(object): 3 | def __init__(self, x): 4 | self.val = x 5 | self.next = None 6 | 7 | class Solution(object): 8 | def reorderList(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: void Do not return anything, modify head in-place instead. 12 | """ 13 | -------------------------------------------------------------------------------- /MainClassTest.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import unittest as unit 4 | from mock import Mock, patch 5 | 6 | import MainClass as mc 7 | 8 | class MainClassTest(unit.TestCase): 9 | def testSayHello(self): 10 | patcher = patch('MainClass.mcp').start() 11 | patcher.say_hello.return_value = "I will not say hello" 12 | mc.mainFunction() 13 | print "finished" 14 | 15 | 16 | -------------------------------------------------------------------------------- /GeneralPractice/MainClassTest.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import unittest as unit 4 | from mock import Mock, patch 5 | 6 | import MainClass as mc 7 | 8 | class MainClassTest(unit.TestCase): 9 | def testSayHello(self): 10 | patcher = patch('MainClass.mcp').start() 11 | patcher.say_hello.return_value = "I will not say hello" 12 | mc.mainFunction() 13 | print "finished" 14 | 15 | 16 | -------------------------------------------------------------------------------- /HackerRankProblems/ASCII Flower.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | line1 = "..O.." 4 | line2 = "O.o.O" 5 | line3 = "..O.." 6 | 7 | 8 | r,c = raw_input().strip().split(' ') 9 | r,c = [int(r),int(c)] 10 | 11 | effectiveLine1 = line1 * c 12 | effectiveLine2 = line2 * c 13 | effectiveLine3 = line3 * c 14 | 15 | for _ in range(r): 16 | print effectiveLine1 17 | print effectiveLine2 18 | print effectiveLine3 19 | 20 | -------------------------------------------------------------------------------- /GeneralPractice/KeyBoardException.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def test_keyboardException(): 5 | 6 | try: 7 | count = 1000000 8 | while count >= 0: 9 | count = count - 1 10 | print "Count is now : ", count 11 | except KeyboardInterrupt as ex: 12 | print "CAUGHT KEYBOARD EXCEPTION : ", ex 13 | print type(ex) 14 | print ex.args 15 | 16 | test_keyboardException() -------------------------------------------------------------------------------- /LeetCodePractice/645. Set Mismatch.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def findErrorNums(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: List[int] 8 | """ 9 | self.dictionary = {} 10 | missing, duplicate = None, None 11 | for i in nums: 12 | if i in self.dictionary: 13 | self.dictionary[i] = self.dictionary[i] + 1 14 | -------------------------------------------------------------------------------- /GeneralPractice/PoolExample.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import multiprocessing 4 | class Solver(object): 5 | def __init__(self): 6 | print "Called init function of solver" 7 | 8 | def __call__(self, *args, **kwargs): 9 | print "In call function solver class" 10 | print args 11 | 12 | 13 | pool=multiprocessing.Pool(4) 14 | result = pool.apply_async(Solver(), args=("abc", "pqr", "lmn")) 15 | result.get() 16 | -------------------------------------------------------------------------------- /LeetCodePractice/721. Accounts Merge.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def accountsMerge(self, accounts): 5 | """ 6 | :type accounts: List[List[str]] 7 | :rtype: List[List[str]] 8 | """ 9 | contacts = [] 10 | for item in accounts: 11 | contacts.append(item[0]) 12 | 13 | by_email = dict(lambda: []) 14 | for item in accounts: 15 | 16 | 17 | -------------------------------------------------------------------------------- /GeneralPractice/1525. Number of Good Ways to Split a String.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def numSplits(self, s): 6 | """ 7 | :type s: str 8 | :rtype: int 9 | """ 10 | 11 | leftHashMap = {} 12 | rightHashMap = {} 13 | 14 | left = Counter() 15 | right = Counter(s) 16 | 17 | for i in range(0, len(s)): 18 | pass 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /LeetCodePractice/Median of Two Sorted Arrays.py: -------------------------------------------------------------------------------- 1 | """ 2 | Not yet complete 3 | """ 4 | 5 | def findMedianSortedArrays(nums1, nums2): 6 | if (len(num1) == len(num2)): 7 | # return float(num) 8 | pass 9 | 10 | 11 | if __name__=="__main__": 12 | num1 = [1, 2] 13 | num2 = [3, 4] 14 | print findMedianSortedArrays(num1, num2) 15 | 16 | num1 = [1, 2] 17 | num2 = [3] 18 | print findMedianSortedArrays(num1, num2) 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /GeneralPractice/SortTuples.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | from itertools import groupby 3 | 4 | 5 | inputList = [ (5,1), (7,4), (1,7,4), (2,4,6,1) ] 6 | 7 | print "Input: ", inputList 8 | 9 | finalResult = [] 10 | for key, group in groupby(inputList, lambda x: len(x)): 11 | for thing in group: 12 | finalResult.append(sorted(thing)) 13 | #print thing, key 14 | 15 | finalResult = list(map(lambda x: tuple(x), finalResult)) 16 | print "Output: ", finalResult -------------------------------------------------------------------------------- /GeneralPractice/HighOrderFunctions.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def logger(msg): 4 | 5 | def log_message(): 6 | print "Your custome message is : ", msg 7 | 8 | return log_message 9 | 10 | log_hi = logger("Hi ! !") 11 | log_hi() 12 | 13 | 14 | def html_tag(tags): 15 | 16 | def mainLine(comment): 17 | print "<{0}>{1}".format(tags, comment) 18 | 19 | return mainLine 20 | 21 | print_h1 = html_tag('h1') 22 | print_h1("First blog") 23 | print_h1("Second blog") 24 | -------------------------------------------------------------------------------- /serverlessPrograms/.serverless/cloudformation-template-create-stack.json: -------------------------------------------------------------------------------- 1 | { 2 | "AWSTemplateFormatVersion": "2010-09-09", 3 | "Description": "The AWS CloudFormation template for this Serverless application", 4 | "Resources": { 5 | "ServerlessDeploymentBucket": { 6 | "Type": "AWS::S3::Bucket" 7 | } 8 | }, 9 | "Outputs": { 10 | "ServerlessDeploymentBucketName": { 11 | "Value": { 12 | "Ref": "ServerlessDeploymentBucket" 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /.idea/CompetitiveProgramming.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | -------------------------------------------------------------------------------- /LeetCodePractice/287. Find the Duplicate Number.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 53 / 53 test cases passed. 5 | Status: Accepted 6 | Runtime: 82 ms 7 | 8 | Beats 9% only 9 | """ 10 | class Solution(object): 11 | def findDuplicate(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: int 15 | """ 16 | counter = 0 17 | for i in nums: 18 | if (counter & 1< 0): 19 | return i 20 | counter = counter | 1<python Basic_AlphaBetaPruning.py 11 | 12 | No external libraries are required. 13 | -------------------------------------------------------------------------------- /CompaniesHiringQuestions/List_Mutability.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def func1(listInput): 4 | listInput[2] = -1 5 | return sorted(listInput) 6 | return listInput 7 | 8 | if __name__ == "__main__": 9 | list1 = [] 10 | list1.append(1) 11 | 12 | print "List1 : ", list1 13 | 14 | list2 = [3, 0, 19, 1, 9] 15 | list3 = [4, 5, 6] 16 | 17 | print "list before: ", list2 18 | print "Calling function" 19 | print "list after: ", func1(list2) 20 | print "list2 as it is : ", list2 21 | 22 | #func1(list) 23 | -------------------------------------------------------------------------------- /HackerRankProblems/Highlight Landmarks.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | """ 3 | Not working fine for last 5 inputs. I guess osme space issues is there. 4 | """ 5 | 6 | if __name__ =="__main__": 7 | string = raw_input('') 8 | n = int(raw_input('')) 9 | landmarks = raw_input('') 10 | landmarks = landmarks.split() 11 | 12 | for landmark in landmarks: 13 | #print " for landmark : ", landmark 14 | string = string.replace(landmark, "" + landmark + "") 15 | 16 | #print " Result : " 17 | print string -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Twitter4.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | start = raw_input('') 5 | end = raw_input('') 6 | n = int(raw_input('')) 7 | 8 | result = [] 9 | for i in range(n): 10 | data = raw_input('') 11 | if ' ' in data: 12 | datSplit = data.split(' ') 13 | dateData = datSplit[0] 14 | if dateData >= start and dateData <= end: 15 | result.append(data) 16 | else: 17 | if data >= start and data <= end: 18 | result.append(data) 19 | 20 | for _d in result: 21 | print _d 22 | -------------------------------------------------------------------------------- /GeneralPractice/ConceptOfFreeVariable.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | #Clousures: 4 | #Inner function has access to variables even when outer function's scope has exited. 5 | #this access of free variables by a function is called a clourse 6 | 7 | # A clousure closes over free variable in its environment.. 8 | 9 | def outer_func(): 10 | mydummyVar = "Hello world ! " 11 | 12 | def inner_func(): 13 | print (mydummyVar) #Free variable as it was not defined within this scope. 14 | return inner_func 15 | 16 | 17 | my_func = outer_func() 18 | -------------------------------------------------------------------------------- /GeneralPractice/max events can be attended.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | from heapq import heappop, heappush 5 | 6 | 7 | class Solution: 8 | def maxEvents(self, events): 9 | events.sort(key=lambda x : x[1]) 10 | book,res=set(),0 11 | for s,e in events: 12 | i=s 13 | while i in book and i<=e: 14 | i+=1 15 | if i<=e: 16 | res+=1 17 | book.add(i) 18 | return res 19 | s=Solution() 20 | print(s.maxEvents( [ [1, 10], [2, 3], [4, 5], [6, 7] ] )) -------------------------------------------------------------------------------- /LeetCodePractice/274. H-Index.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def hIndex(self, citations): 5 | """ 6 | :type citations: List[int] 7 | :rtype: int 8 | """ 9 | 10 | citations = sorted(citations, reverse=True) 11 | #print citations 12 | result = [] 13 | for i in range(len(citations)): 14 | if citations[i] == i+1: 15 | result.append(citations[i]) 16 | 17 | return max(result) 18 | 19 | s=Solution() 20 | print s.hIndex([3, 0, 6, 1, 5]) -------------------------------------------------------------------------------- /Internships/Veritas/Array Reduction: -------------------------------------------------------------------------------- 1 | def reductionCost(num): 2 | 3 | sumT = 0 4 | sumArray = [] 5 | num = sorted(num) 6 | if (len(num) == 2): 7 | return num[0] + num[1] 8 | 9 | i = 0 10 | while(i < len(num)): 11 | if (i == 0): 12 | sumT = num[i] + num[i + 1] 13 | i = i + 2 14 | else: 15 | sumT = sumT + num[i] 16 | i = i + 1 17 | sumArray.append(sumT) 18 | return sum(sumArray) 19 | 20 | 21 | 22 | 23 | if __name__ == "__main__": 24 | print reductionCost([4, 3, 2, 1]) 25 | 26 | -------------------------------------------------------------------------------- /MainClass.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import MainClassHelper as mcp 4 | 5 | 6 | def mainFunction(): 7 | val = mcp.say_hello() 8 | print val 9 | 10 | subjects = {} 11 | subjects['a'] = 3 12 | subjects['b'] = 2 13 | subjects['c'] = 1 14 | 15 | def make_comparator(): 16 | def compare(x, y): 17 | if x[1] < y[1]: 18 | return -1 19 | elif (x[1] > y[1]): 20 | return 1 21 | return 0 22 | return compare 23 | 24 | print subjects 25 | sortedDict = sorted(subjects.items(), cmp=make_comparator(), reverse=True) 26 | print sortedDict -------------------------------------------------------------------------------- /LeetCodePractice/461. Hamming Distance.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 5 | 149 / 149 test cases passed. 6 | Status: Accepted 7 | Runtime: 52 ms 8 | """ 9 | class Solution(object): 10 | def hammingDistance(self, x, y): 11 | """ 12 | :type x: int 13 | :type y: int 14 | :rtype: int 15 | """ 16 | res = x^y 17 | count = 0 18 | while(res > 0): 19 | if (res & 1): 20 | count = count + 1 21 | res = res >> 1 22 | return count 23 | 24 | s=Solution() 25 | print s.hammingDistance(1, 4) -------------------------------------------------------------------------------- /GeneralPractice/MainClass.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import MainClassHelper as mcp 4 | 5 | 6 | def mainFunction(): 7 | val = mcp.say_hello() 8 | print val 9 | 10 | subjects = {} 11 | subjects['a'] = 1 12 | subjects['b'] = 2 13 | subjects['c'] = 3 14 | 15 | def make_comparator(): 16 | def compare(x, y): 17 | if x[1] < y[1]: 18 | return -1 19 | elif (x[1] > y[1]): 20 | return 1 21 | return 0 22 | return compare 23 | 24 | print subjects 25 | sortedDict = sorted(subjects.items(), cmp=make_comparator(), reverse=True) 26 | print sortedDict -------------------------------------------------------------------------------- /CompaniesHiringQuestions/MicrosoftCoding_TowerOfHanaoi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Microsoft coding challenge 3 | Accepted solution 4 | """ 5 | 6 | if __name__ =="__main__": 7 | 8 | lines = [line.rstrip('\r\n') for line in open('/Users/deepika/Desktop/MicrosoftExam/_3/PracticeInput.txt')] 9 | for line in lines: 10 | line = line.split(',') 11 | #print "line = ", line 12 | ndisk = line[0] 13 | fromPeg = line[1] 14 | toPeg = line[2] 15 | result = [] 16 | if fromPeg == toPeg: 17 | print "0" 18 | else: 19 | print pow(2,int(ndisk)) - 1 20 | -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Balance Point.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def balancePoint(arr): 5 | 6 | sumLeft = 0 7 | for i in range(len(arr)): 8 | sumLeft = sumLeft + arr[i] 9 | 10 | sumRight = arr[len(arr) - 1]; 11 | sumLeft = sumLeft - arr[len(arr) - 1] 12 | for i in range(len(arr) - 2, -1, -1): 13 | if (sumRight == sumLeft - arr[i]): 14 | return i 15 | 16 | sumRight = sumRight + arr[i] 17 | sumLeft = sumLeft - arr[i] 18 | 19 | return -1; 20 | 21 | if __name__=="__main__": 22 | print balancePoint([1, 2, 3, 3]) 23 | 24 | #arr[0], arr[1], arr[2], arr[3] -------------------------------------------------------------------------------- /CompaniesHiringQuestions/amazon1.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def minimumTime(numOfSubFiles, files): 5 | if (numOfSubFiles == 1): 6 | return files[0] 7 | if (numOfSubFiles == 2): 8 | return files[0] + file[1] 9 | 10 | files = sorted(files) 11 | totalTime = files[0] + files[1] 12 | cummulative = totalTime 13 | 14 | i = 2 15 | while (i < numOfSubFiles): 16 | totalTime += files[i] 17 | cummulative += totalTime 18 | i = i + 1 19 | 20 | return cummulative 21 | 22 | 23 | print(minimumTime(4, [4, 8, 6, 12])) 24 | print(minimumTime(4, [20, 4, 8, 2])) 25 | -------------------------------------------------------------------------------- /LeetCodePractice/Remove Duplicate Letters.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution(object): 3 | def removeDuplicateLetters(self, s): 4 | """ 5 | :type s: str 6 | :rtype: str 7 | """ 8 | result=[] 9 | counter = 0; 10 | start = 0 11 | end = 0; 12 | for i in range(len(s)): 13 | if (counter & 1<<(i-'a') > 0): #Not the first occurence 14 | pass 15 | else: 16 | end = end + 1 17 | 18 | 19 | s=Solution() 20 | print s.removeDuplicateLetters("bcabc") #expected "abc" 21 | print s.removeDuplicateLetters("cbacdcbc") #Expected "acdb" -------------------------------------------------------------------------------- /Leetcode_Challenge/Sep 24/Convert a Number to Hexadecimal.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | The logic is not correct here. 4 | """ 5 | def toHex(num): 6 | result = '' 7 | while(num > 0): 8 | if (num >= 16): 9 | remainder = num % 16; 10 | quotient = num/16; 11 | result = result + "012345689ABCDEF"[quotient] 12 | num = remainder 13 | else: 14 | result = result + "012345689ABCDEF"[num-1] 15 | num = 0; #to exit the loop 16 | print "Updating result to : ", result 17 | return result 18 | 19 | if __name__=="__main__": 20 | num = 48 21 | print toHex(num) -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Zappos_1.21 Gigawatts.py: -------------------------------------------------------------------------------- 1 | """ 2 | Zappos coding challenge 3 | 4 | Given two arrays. find if the there are two elements in batteryOne,batteryTwo such that 5 | sum of the two is target 6 | """ 7 | 8 | if __name__=="__main__": 9 | batteryOne = raw_input('') 10 | batteryTwo = raw_input('') 11 | target = int(raw_input('')) 12 | 13 | batteryOne = [ target - int(x) for x in batteryOne.split()] 14 | batteryTwo = [ int(x) for x in batteryTwo.split()] 15 | 16 | s = filter(lambda x : x in batteryTwo, batteryOne) 17 | if len(s) > 0: 18 | print "True" 19 | else: 20 | print "False" 21 | 22 | -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Microsoft_3 numbers with even occurence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers,there are 3 numbers which occur even number of times. 3 | Find those numbers and print them in the order they first appear in the array. 4 | """ 5 | 6 | 7 | def displayNumbers(numbers): 8 | 9 | odd = 0 10 | even = 0 11 | 12 | for i in numbers: 13 | if (1< 0: #Actually an even occurence 14 | #Unset from even number 15 | even |= 1< 0: 18 | qq.add(e - n) 19 | q = qq 20 | res += 1 21 | return res 22 | 23 | s=Solution() 24 | print(s.numSquares(12)) 25 | print(s.numSquares(13)) -------------------------------------------------------------------------------- /LeetCodePractice/657. Judge Route Circle.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def judgeCircle(self, moves): 5 | """ 6 | :type moves: str 7 | :rtype: bool 8 | """ 9 | start = [0, 0] 10 | for pos in moves: 11 | if pos == 'U': 12 | start[1] += 1 13 | elif pos == 'D': 14 | start[1] -= 1 15 | elif pos == 'R': 16 | start[0] += 1 17 | else: 18 | start[0] -= 1 19 | 20 | return start == [0, 0] 21 | 22 | s=Solution() 23 | assert s.judgeCircle("UD") == True 24 | assert s.judgeCircle("LL") == False -------------------------------------------------------------------------------- /DL_Safari.py: -------------------------------------------------------------------------------- 1 | import theano 2 | from theano import tensor as T, function 3 | 4 | import numpy as np 5 | 6 | def simpleFunction(): 7 | X=T.matrix('x') 8 | Y=X**2 9 | F = function([X], [Y]) 10 | print X 11 | print Y 12 | print F 13 | 14 | x=np.ones((2,2))*3 15 | y=F(x) 16 | print "========" 17 | print x 18 | print y 19 | 20 | def simpleFunctionWithDerivative(): 21 | X=T.matrix('x') 22 | Y=X**2 23 | Z = T.grad(Y.sum(), X) 24 | F = function([X], [Y, Z]) 25 | 26 | x=np.ones((2,2))*3 27 | y, z =F(x) 28 | print "========" 29 | print x 30 | print y 31 | print z 32 | 33 | simpleFunctionWithDerivative() 34 | 35 | -------------------------------------------------------------------------------- /LeetCodePractice/Excel Sheet Column Number.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | 171. Excel Sheet Column Number 4 | """ 5 | 6 | def titleToNumber(s): 7 | mapping = dict() 8 | for i in range(26): 9 | mapping[chr(i + 65)] = i + 1 10 | 11 | result = 0 12 | powerCount = 0 13 | #print type(s[0]) 14 | #print chr(ord(s[0])), mapping.get(chr(ord(s[0]))) 15 | for i in range(len(s), 0, -1): 16 | result = result + pow(26, powerCount) * mapping.get(chr(ord(s[i-1]))) 17 | powerCount = powerCount + 1 18 | return result 19 | 20 | if __name__ == "__main__": 21 | 22 | s = "AA" 23 | print titleToNumber(s) 24 | s = "AB" 25 | print titleToNumber(s) 26 | 27 | -------------------------------------------------------------------------------- /GeneralPractice/1389. Create Target Array in the Given Order.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Details 5 | Runtime: 20 ms, faster than 77.41% of Python online submissions for Create Target Array in the Given Order. 6 | Memory Usage: 13.7 MB, less than 12.81% of Python online submissions for Create Target Array in the Given Order. 7 | """ 8 | class Solution(object): 9 | def createTargetArray(self, nums, index): 10 | """ 11 | :type nums: List[int] 12 | :type index: List[int] 13 | :rtype: List[int] 14 | """ 15 | 16 | result = [] 17 | for i in range(len(nums)): 18 | result.insert(index[i], nums[i]) 19 | return result -------------------------------------------------------------------------------- /GeneralPractice/1408. String Matching in an Array.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def stringMatching(self, words): 6 | """ 7 | :type words: List[str] 8 | :rtype: List[str] 9 | """ 10 | 11 | result = set() 12 | for word1 in words: 13 | for word2 in words: 14 | if word1 == word2: 15 | continue 16 | if word2 in word1: 17 | result.add(word2) 18 | return result 19 | 20 | s=Solution() 21 | print(s.stringMatching(words = ["mass","as","hero","superhero"])) 22 | print(s.stringMatching(["leetcoder","leetcode","od","hamlet","am"])) -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Twitter2.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | #Max subarray with sum lees than equal to k 5 | 6 | import sys 7 | def maxLength(a, k): 8 | 9 | cur_sum = a[0] 10 | max_len = 1 11 | start = 0 12 | 13 | for i in range(1, len(a)): 14 | while cur_sum > k and start < i: 15 | cur_sum -= a[start] 16 | start = start + 1 17 | 18 | if cur_sum <= k: 19 | max_len = max(max_len, i - start) 20 | 21 | cur_sum = cur_sum + a[i] 22 | 23 | if cur_sum <= k: 24 | max_len = max(max_len, i - start + 1) 25 | 26 | return max_len 27 | 28 | 29 | print maxLength([3,1,2,1], 4) 30 | #print maxLength([1,2,3 ], 4) -------------------------------------------------------------------------------- /NewLeetCodeProblems/1017. Convert to Base -2.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | class Solution(object): 3 | 4 | def baseNeg2(self, N): 5 | """ 6 | :type N: int 7 | :rtype: str 8 | """ 9 | if N == 0: 10 | return "0" 11 | res = "" 12 | while N != 0: 13 | dividend = N / -2 14 | if N % 2 == 0 : #even 15 | res += "0" 16 | else: 17 | res += "1" 18 | N = dividend 19 | 20 | return res[::-1] 21 | 22 | s=Solution() 23 | print(s.baseNeg2(2)) 24 | print(s.baseNeg2(3)) 25 | print(s.baseNeg2(4)) 26 | print(s.baseNeg2(6)) 27 | print(s.baseNeg2(8)) 28 | print(s.baseNeg2(15)) 29 | -------------------------------------------------------------------------------- /HackerRankProblems/LeftRotate.py: -------------------------------------------------------------------------------- 1 | 2 | import collections 3 | 4 | def rotate(arr, d): 5 | arr = collections.deque(arr) 6 | arr.rotate(-d) 7 | #print type(arr) 8 | return arr 9 | 10 | if __name__ =="__main__": 11 | dn=raw_input() 12 | dn=dn.split() 13 | n=int(dn[0]) 14 | d=int(dn[1]) 15 | 16 | arr=raw_input() 17 | arr=list(arr) 18 | arr = list(rotate(arr, d)) 19 | 20 | result = "" 21 | for item in arr: 22 | if (item == ' '): 23 | continue 24 | else: 25 | if (result == ""): 26 | result = str(item) + " " 27 | else: 28 | result = result + str(item) + " " 29 | print result.strip() 30 | -------------------------------------------------------------------------------- /LeetCodePractice/Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | 26. Remove Duplicates from Sorted Array 4 | """ 5 | def removeDuplicates(nums): 6 | N = len(nums) 7 | i = 1; 8 | start = 0; 9 | while(i < N): 10 | if (nums[i] == nums[i-1]): 11 | i = i + 1 12 | continue 13 | else: 14 | nums[start + 1] = nums[i] 15 | start = start + 1; 16 | i = i + 1 17 | #print "Nums just before returning : ", nums 18 | return nums[0:start+1] 19 | 20 | if __name__ == "__main__": 21 | nums = [1, 1, 2, 3, 4, 5 , 6, 6, 7, 7, 8] 22 | result = removeDuplicates(nums); 23 | print len(result) 24 | #print "After Actual result : ", nums -------------------------------------------------------------------------------- /GeneralPractice/617. Merge Two Binary Trees.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode(object): 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | class Solution(object): 9 | def mergeTrees(self, t1, t2): 10 | """ 11 | :type t1: TreeNode 12 | :type t2: TreeNode 13 | :rtype: TreeNode 14 | """ 15 | if t1 is None: 16 | return t2 17 | if t2 is None: 18 | return t1 19 | 20 | t1.val = t1.val + t2.val 21 | t1.left = self.mergeTrees(t1.left, t2.left) 22 | t1.right = self.mergeTrees(t1.right, t2.right) 23 | 24 | return t1 25 | -------------------------------------------------------------------------------- /LeetCodePractice/651. 4 Keys Keyboard.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """This is a wrong approach. It can be solved by DP 4 | """ 5 | class Solution(object): 6 | def maxA(self, N): 7 | """ 8 | :type N: int 9 | :rtype: int 10 | """ 11 | if N == 1: 12 | return 1 13 | if N == 2: 14 | return 2 15 | if N == 3: 16 | return 3 17 | if N == 4: 18 | return 4 19 | if N == 5: 20 | return 5 21 | 22 | n_half = N/2 23 | remaining_v = N - n_half - 2 24 | return n_half * (remaining_v + 1) 25 | 26 | s=Solution() 27 | for i in range(1, 51): 28 | print " For i = ", i, " ", s.maxA(i) 29 | -------------------------------------------------------------------------------- /LeetCodePractice/100. Same Tree.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 54 / 54 test cases passed. 5 | Status: Accepted 6 | Runtime: 28 ms 7 | """ 8 | class TreeNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | class Solution(object): 15 | def isSameTree(self, p, q): 16 | """ 17 | :type p: TreeNode 18 | :type q: TreeNode 19 | :rtype: bool 20 | """ 21 | if p is None and q is None: 22 | return True 23 | if (p and not q) or (not p and q): 24 | return False 25 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) -------------------------------------------------------------------------------- /LeetCodePractice/238. Product of Array Except Self.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | """ 3 | 17 / 17 test cases passed. 4 | Status: Accepted 5 | Runtime: 172 ms 6 | """ 7 | 8 | class Solution(object): 9 | def productExceptSelf(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: List[int] 13 | """ 14 | ret = [] 15 | prefix = 1 16 | for i in range(len(nums)): 17 | ret.append(prefix) 18 | prefix = prefix * nums[i] 19 | 20 | suffix = 1 21 | for i in range(len(nums) - 1, -1, -1): 22 | ret[i] = ret[i]*suffix 23 | suffix = suffix * nums[i] 24 | return ret 25 | 26 | s=Solution() 27 | print s.productExceptSelf([1, 2, 3,4]) -------------------------------------------------------------------------------- /LeetCodePractice/452. Minimum Number of Arrows to Burst Balloons.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 43 / 43 test cases passed. 5 | Status: Accepted 6 | Runtime: 135 ms 7 | """ 8 | class Solution(object): 9 | def findMinArrowShots(self, points): 10 | """ 11 | :type points: List[List[int]] 12 | :rtype: int 13 | """ 14 | 15 | points = sorted(points, key = lambda x: x[1]) 16 | 17 | res, end = 0, -float('inf') 18 | for _p in points: 19 | if _p[0] > end: 20 | res = res + 1 21 | end = _p[1] 22 | return res 23 | 24 | s=Solution() 25 | print s.findMinArrowShots([[1,2],[3,4],[5,6],[7,8]]) 26 | print s.findMinArrowShots([[10,16], [2,8], [1,6], [7,12]]) 27 | -------------------------------------------------------------------------------- /Internships/Bloomberg/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | if __name__ == "__main__": 5 | 6 | N = int(raw_input('')) 7 | names = list() 8 | 9 | #codes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73, 79,83,89,97, 101] 10 | anagrams = dict() 11 | #print len(codes) 12 | for i in range(N): 13 | name = raw_input('') 14 | name = name.lower() 15 | name1 = "".join(sorted(name)) 16 | 17 | if (anagrams.get(name1, -1) == -1): 18 | anagrams[name1] = 1 19 | else: 20 | anagrams[name1] = anagrams.get(name1) + 1 21 | 22 | count = 0 23 | for i, items in anagrams.items(): 24 | if (items > 1): 25 | count = count + items 26 | 27 | #print anagrams 28 | print count 29 | -------------------------------------------------------------------------------- /LeetCodePractice/301. Remove Invalid Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeInvalidParentheses(self, s): 3 | """ 4 | :type s: str 5 | :rtype: List[str] 6 | """ 7 | str = list(s) 8 | stack = [] 9 | for i in range(len(str)): 10 | if str[i] == '(': 11 | stack.append(i) 12 | elif str[i] == ')': 13 | if not stack: 14 | #print "Hit this for str : ", str, " at i = ",i 15 | str[i] = '*' 16 | else: 17 | stack.pop() 18 | 19 | for i in stack: 20 | str[i] = '*' 21 | 22 | return ''.join(str).replace('*', '') 23 | 24 | s=Solution() 25 | print s.removeInvalidParentheses("()())()") -------------------------------------------------------------------------------- /GeneralPractice/1614. Maximum Nesting Depth of the Parentheses.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | """ 5 | Details 6 | Runtime: 20 ms, faster than 59.57% of Python online submissions for Maximum Nesting Depth of the Parentheses. 7 | Memory Usage: 13.5 MB, less than 45.57% of Python online submissions for Maximum Nesting Depth of the Parentheses. 8 | """ 9 | class Solution(object): 10 | def maxDepth(self, s): 11 | """ 12 | :type s: str 13 | :rtype: int 14 | """ 15 | 16 | depth = 0 17 | maxD = -1 18 | for i in range(len(s)): 19 | if s[i] == '(': 20 | depth += 1 21 | elif s[i] == ')' and depth > 0: 22 | depth -= 1 23 | maxD = max(maxD, depth) 24 | return maxD 25 | -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Bloomberg.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | import sys 3 | #output = [sys.maxint]*len("ABCSD") 4 | #print output 5 | """ 6 | Given a string 7 | """ 8 | 9 | 10 | def function(string, key): 11 | arr = [0 for i in range(len(string))] 12 | leftIndex = sys.maxint 13 | for i in range(len(string)): 14 | if string[i] == key: 15 | leftIndex = i 16 | arr[i] = 0 17 | else: 18 | arr[i] = abs(i - leftIndex) 19 | 20 | 21 | rightIndex = sys.maxint 22 | for i in range(len(string)-1, -1, -1): 23 | if string[i] == key: 24 | rightIndex = i 25 | else: 26 | arr[i] = min(arr[i], abs(i - rightIndex)) 27 | 28 | print arr 29 | 30 | function("BLOOMBERG", "B") 31 | 32 | length = [] 33 | print length -------------------------------------------------------------------------------- /GeneralPractice/Google Monarchy.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class TreeNode(object): 4 | def __init__(self, x): 5 | self.val = x 6 | self.left = None 7 | self.right = None 8 | 9 | class Solution: 10 | def traverse(self,root): 11 | if root is None: 12 | return 13 | 14 | print(root.val) 15 | self.traverse(root.left) 16 | self.traverse(root.right) 17 | 18 | 19 | t=TreeNode("king") 20 | t.left=TreeNode("a1") 21 | t.right=TreeNode("a2") 22 | t.left.left=TreeNode("b1") 23 | t.left.right=TreeNode("b2") 24 | t.right.left=TreeNode("c1") 25 | t.right.right=TreeNode("c2") 26 | t.left.left.left=TreeNode("d1") 27 | t.left.left.right=TreeNode("d2") 28 | t.left.right.right=TreeNode("d3") 29 | 30 | s=Solution() 31 | print(s.traverse(t)) 32 | -------------------------------------------------------------------------------- /Internships/Twitter/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Subaarray of less than equal to k 4 | """ 5 | 6 | def maxLength(a, k): 7 | results = [] 8 | 9 | max_so_far = 0 10 | max_ending_here = 0 11 | i = 0 12 | while( i < len(a)): 13 | max_ending_here = max(0, max_ending_here + a[i]) 14 | if (max_ending_here >= max_so_far and max_ending_here <= k): 15 | max_so_far = max(max_so_far, max_ending_here) 16 | results.append(max_so_far) 17 | i = i + 1 18 | continue 19 | else: 20 | max_ending_here = 0 21 | max_so_far = 0 22 | #start from the same i hwere the k was exceeed 23 | return max(results) 24 | 25 | 26 | 27 | if __name__ == "__main__": 28 | arr = [1, 2, 3] 29 | print maxLength(arr, 4) -------------------------------------------------------------------------------- /LeetCodePractice/643. Maximum Average Subarray I.py: -------------------------------------------------------------------------------- 1 | """ 2 | Accepted solution: Sliding window kind of slution. 3 | 4 | """ 5 | class Solution(object): 6 | def findMaxAverage(self, nums, k): 7 | """ 8 | :type nums: List[int] 9 | :type k: int 10 | :rtype: float 11 | """ 12 | n = len(nums) 13 | sum_so_far = 0 14 | for i in range(k): 15 | sum_so_far = sum_so_far + nums[i] 16 | curr_sum = sum_so_far 17 | for i in range(k, n): 18 | #print('i: ', i) 19 | #print "popped :", 20 | curr_sum = curr_sum + (nums[i] - nums[i-k]) 21 | sum_so_far = max(sum_so_far, curr_sum) 22 | return sum_so_far*1.0/k 23 | 24 | s=Solution() 25 | print s.findMaxAverage([1,12,-5,-6,50,3], 4) 26 | -------------------------------------------------------------------------------- /LeetCodePractice/805. Split Array With Same Average.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def splitArraySameAverage(self, A): 5 | """ 6 | :type A: List[int] 7 | :rtype: bool 8 | """ 9 | if len(A) in [0, 1]: 10 | return False 11 | 12 | sumTotal = sum(A) 13 | numbers = len(A) 14 | 15 | sumleft = A[0] 16 | numleft = 1 17 | for i in range(1, len(A)): 18 | sumRight = sumTotal - sumleft 19 | numRight = numbers - numleft 20 | 21 | if sumleft * numRight == sumRight * numleft: 22 | return True 23 | sumleft += A[i] 24 | numleft += 1 25 | return False 26 | 27 | s=Solution() 28 | print s.splitArraySameAverage([1,2,3,4,5,6,7,8]) -------------------------------------------------------------------------------- /LeetCodePractice/Contains Duplicate II.py: -------------------------------------------------------------------------------- 1 | """ 2 | 219. Contains Duplicate II 3 | 4 | 20 / 20 test cases passed. 5 | Status: Accepted 6 | Runtime: 69 ms 7 | Beats : 22% 8 | """ 9 | class Solution(object): 10 | def containsNearbyDuplicate(self, nums, k): 11 | """ 12 | :type nums: List[int] 13 | :type k: int 14 | :rtype: bool 15 | """ 16 | tracker=dict() 17 | for i in range(len(nums)): 18 | if (tracker.get(nums[i], -1) == -1): 19 | tracker[nums[i]] = i 20 | else: # Found duplicate 21 | old_i = tracker[nums[i]] 22 | if ( i - old_i <= k): 23 | return True 24 | else:#Repeat but after k elements 25 | tracker[nums[i]]=i 26 | return False -------------------------------------------------------------------------------- /GeneralPractice/162. Find Peak Element.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def findPeakElement(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: int 9 | """ 10 | if (len(nums) == 1): 11 | return 0; 12 | if (len(nums) == 2): 13 | if (nums[0] > nums[1]): 14 | return 0 15 | return 1 16 | 17 | for i in range(1, len(nums) - 1): 18 | if nums[i] == nums[i+1]: 19 | continue 20 | else: 21 | if (nums[i] > nums[i - 1] and i + 1 < len(nums) and nums[i] > nums[i + 1]): 22 | return i 23 | return 0 24 | 25 | s=Solution() 26 | print(s.findPeakElement([1,2,3,1])) 27 | print(s.findPeakElement([1,2,1,3,5,6,4])) -------------------------------------------------------------------------------- /LeetCodePractice/Same Tree.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | 54 / 54 test cases passed. 4 | Status: Accepted 5 | Runtime: 42 ms 6 | """ 7 | # Definition for a binary tree node. 8 | class TreeNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | class Solution(object): 15 | def isSameTree(self, p, q): 16 | """ 17 | :type p: TreeNode 18 | :type q: TreeNode 19 | :rtype: bool 20 | """ 21 | if (p is None and q is None): 22 | return True 23 | if (p is None and q is not None): 24 | return False 25 | if (p is not None and q is None): 26 | return False 27 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 28 | -------------------------------------------------------------------------------- /LeetCodePractice/Single Element in a Sorted Array.py: -------------------------------------------------------------------------------- 1 | """ 2 | 7 / 7 test cases passed. 3 | Status: Accepted 4 | Runtime: 46 ms 5 | 6 | #later realised since it was sorted in any case binary search makes more sense as this code take O(n) 7 | # whereas binary search will take O(log n) 8 | """ 9 | 10 | class Solution(object): 11 | def singleNonDuplicate(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: int 15 | """ 16 | if (len(nums) == 1): 17 | return nums[0] 18 | else: 19 | xoredSum = 1 20 | for num in nums: 21 | xoredSum = xoredSum ^ int(num) 22 | xoredSum = xoredSum ^ 1 23 | return xoredSum 24 | 25 | s=Solution() 26 | print s.singleNonDuplicate([1,1,2]) 27 | print s.singleNonDuplicate([0,1,1]) -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Expedia2.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import math 4 | 5 | def nCr(n,r): 6 | f = math.factorial 7 | return f(n) / f(r) / f(n-r) 8 | 9 | def volleyball( A, B): 10 | 11 | if A==0 and B==0: 12 | return 1 13 | elif A<0 or B<0: 14 | return 0 15 | elif A<25 and B<25: 16 | return nCr(A+B, A) 17 | else: 18 | if A >= 25 or B >= 25: 19 | if A == 25 and B < 24: 20 | return nCr(24+B, B) 21 | elif B == 25 and A < 24: 22 | return nCr(24+A, A) 23 | if abs(A - B) == 2: 24 | return nCr(48, 24) * 2^(B-24) 25 | else: 26 | print "Dunno 1" 27 | else: 28 | print "dunno2", A, B 29 | 30 | print volleyball(3, 25) 31 | print volleyball(24, 17) -------------------------------------------------------------------------------- /HackerRankProblems/Counting Binary Substrings.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | def count(s): 4 | n=len(s) 5 | matrix=[ [0 for _ in range(n)] for _ in range(n)] 6 | 7 | newS=[] 8 | print matrix 9 | 10 | for item in s: 11 | if (item =='0'): 12 | newS.append(1) 13 | else: 14 | newS.append(-1) 15 | 16 | print newS, newS[1] 17 | result=0 18 | for i in range(n): 19 | for j in range(n): 20 | #print i, j 21 | if (i == j): 22 | matrix[i][i]=newS[j] 23 | elif(j > i): 24 | matrix[i][j]=matrix[i][j-1] + newS[j] 25 | if (matrix[i][j] == 0): 26 | result = result + 1 27 | 28 | print matrix, result 29 | 30 | if __name__=="__main__": 31 | s="00110" 32 | print count(s) -------------------------------------------------------------------------------- /LeetCodePractice/22. Generate Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generateParenthesis(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[str] 6 | """ 7 | result = [] 8 | self.generateParenthesisUtil("", result, n, n) 9 | return result 10 | 11 | def generateParenthesisUtil(self, string_so_far, result, left, right): 12 | if (left > right): 13 | return 14 | if left: 15 | self.generateParenthesisUtil(string_so_far + '(', result, left-1, right) 16 | if (right > left): 17 | self.generateParenthesisUtil( string_so_far + ')', result, left, right-1) 18 | if not right: 19 | result.append(string_so_far) 20 | return 21 | 22 | s=Solution() 23 | print s.generateParenthesis(3) 24 | -------------------------------------------------------------------------------- /LeetCodePractice/121. Best Time to Buy and Sell Stock.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | """ 3 | 200 / 200 test cases passed. 4 | Status: Accepted 5 | Runtime: 39 ms 6 | 7 | Better than 85.58% 8 | """ 9 | class Solution(object): 10 | def maxProfit(self, prices): 11 | """ 12 | :type prices: List[int] 13 | :rtype: int 14 | """ 15 | if (len(prices) in [0, 1]): 16 | return 0 17 | min_ele = prices[0] 18 | profit = 0 19 | for i in range(len(prices)): 20 | if (prices[i] > min_ele): 21 | profit = max(profit, prices[i] - min_ele) 22 | if (prices[i] < min_ele): 23 | min_ele = prices[i] 24 | return profit 25 | 26 | 27 | s=Solution() 28 | assert(s.maxProfit([7, 1, 5, 3, 6, 4]) == 5) 29 | assert(s.maxProfit([7, 6, 4, 3, 1]) == 0) -------------------------------------------------------------------------------- /LeetCodePractice/451. Sort Characters By Frequency.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | """ 3 | 35 / 35 test cases passed. 4 | Status: Accepted 5 | Runtime: 129 ms 6 | """ 7 | class Solution(object): 8 | def frequencySort(self, s): 9 | """ 10 | :type s: str 11 | :rtype: str 12 | """ 13 | dictionary = {} 14 | for _ in s: 15 | if (dictionary.get(_, None) == None): 16 | dictionary[_] = 1 17 | else: 18 | dictionary[_] = dictionary[_] + 1 19 | 20 | 21 | sortedDict = sorted(dictionary.items(), key=(lambda x: x[1]), reverse=True) 22 | result = [k*v for (k, v) in sortedDict] 23 | return "".join(result) 24 | 25 | 26 | s=Solution() 27 | print s.frequencySort("tree") 28 | print s.frequencySort("cccaaa") 29 | print s.frequencySort("Aabb") 30 | -------------------------------------------------------------------------------- /Internships/Kabam/ElectionWinner.py: -------------------------------------------------------------------------------- 1 | def electionWinner(votes): 2 | result = dict() 3 | for item in votes: 4 | if (result.get(item, -1) == - 1): 5 | result[item] = 1 6 | else: 7 | result[item] = result[item] + 1 8 | 9 | 10 | result=sorted(result.items(), key=lambda x: x[1], reverse=True) 11 | #print type(result) 12 | max_votes = result[0][1] 13 | if (len(result) <= 1): 14 | return result[0][0] 15 | else: 16 | name_result=[] 17 | for item in result: 18 | if (item[1] == max_votes): 19 | name_result.append(item[0]) 20 | 21 | name_result = sorted(name_result, reverse=True) 22 | return name_result[0] 23 | #print max_votes 24 | 25 | 26 | if __name__=="__main__": 27 | 28 | print electionWinner(["A","A", "C", "B", "B", ""]); -------------------------------------------------------------------------------- /LeetCodePractice/560. Subarray Sum Equals K.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Not correct 5 | """ 6 | 7 | class Solution(object): 8 | def subarraySum(self, nums, k): 9 | """ 10 | :type nums: List[int] 11 | :type k: int 12 | :rtype: int 13 | """ 14 | start, end = 0, 0 15 | sumTotal = 0 16 | count = 0 17 | while start < len(nums): 18 | while ( sumTotal > k and start < len(nums) ): 19 | sumTotal -= nums[start] 20 | start = start + 1 21 | if sumTotal == k: 22 | count = count + 1 23 | if end < len(nums): 24 | sumTotal += nums[end] 25 | end = end + 1 26 | 27 | 28 | return count 29 | s=Solution() 30 | #print s.subarraySum([1,1,1], 2) 31 | print(s.subarraySum([1, 2, 3], 3)) -------------------------------------------------------------------------------- /Leetcode_Challenge/Sep 24/Left Leaves Sum.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Accepted soution 4 | """ 5 | class TreeNode(object): 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | class Solution(object): 12 | def sumOfLeftLeaves(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | if ( root is None): 18 | return 0 19 | sum = 0; 20 | if (root.left is not None and root.left.left is None and root.left.right is None): 21 | #print "found Leaf" , root.left.val 22 | sum = sum + root.left.val 23 | sumL = self.sumOfLeftLeaves(root.left) 24 | sumR = self.sumOfLeftLeaves(root.right) 25 | return sum + sumL + sumR 26 | 27 | if __name__ == "__main__": 28 | sol = Solution() 29 | -------------------------------------------------------------------------------- /GeneralPractice/621. Task Scheduler.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def leastInterval(self, tasks, n): 6 | """ 7 | :type tasks: List[str] 8 | :type n: int 9 | :rtype: int 10 | """ 11 | 12 | hashMap = [ 0 for i in range(26)] 13 | for t in tasks: 14 | hashMap[ord(t) - ord('A')] = hashMap[ord(t) - ord('A')] + 1 15 | 16 | hashMap.sort() 17 | 18 | max_value = max(hashMap) - 1 19 | 20 | slots = max_value * n 21 | 22 | i = 24 23 | while i >= 0: 24 | _inp = hashMap[i] 25 | slots = slots - min(_inp, max_value) 26 | i = i - 1 27 | if slots > 0: 28 | return slots + len(tasks) 29 | 30 | return len(tasks) 31 | s=Solution() 32 | print(s.leastInterval(["A","A","A","B","B","B"], 2)) -------------------------------------------------------------------------------- /LeetCodePractice/386. Lexicographical Numbers.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | 6 | def lexicalOrder(self, n): 7 | """ 8 | :type n: int 9 | :rtype: List[int] 10 | """ 11 | numbers = [str(x) for x in range(1, n+1)] 12 | 13 | def less_than(x, y): 14 | return x < y 15 | 16 | 17 | def make_comparator(): 18 | def compare(x, y): 19 | if less_than(x, y): 20 | return -1 21 | elif less_than(y, x): 22 | return 1 23 | else: 24 | return 0 25 | return compare 26 | 27 | numbers = sorted(numbers, cmp=make_comparator()) 28 | numbers = [int(x) for x in numbers] 29 | return numbers 30 | 31 | s=Solution() 32 | print s.lexicalOrder(13) -------------------------------------------------------------------------------- /LeetCodePractice/91. Decode Ways.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def numDecodings(self, s): 6 | """ 7 | :type s: str 8 | :rtype: int 9 | """ 10 | if len(s) == 0: 11 | return 0 12 | if (len(s) == 1): 13 | return 1 14 | i = 0 15 | count = 1 #For all single integer case 16 | 17 | while i < len(s) - 1: 18 | main_part = s[i:i+2] 19 | if main_part >= '10' and main_part <= '26': 20 | print(main_part) 21 | count += self.numDecodings(s[0:i]) + 1 + self.numDecodings(s[i+2:]) 22 | i = i + 1 23 | return count 24 | 25 | s=Solution() 26 | #print s.numDecodings("12") 27 | print s.numDecodings("226") 28 | #assert s.numDecodings("12") == 2 29 | #assert s.numDecodings("226") == 3 30 | 31 | -------------------------------------------------------------------------------- /GeneralPractice/Temp.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | def socool(tasks, coolTime): 4 | cooldown = {} 5 | time = 0 6 | for task in tasks: 7 | if task not in cooldown: 8 | cooldown[task] = coolTime #A -> 2 9 | for key in cooldown.keys(): #A -> 0, B -> 0 10 | if cooldown[key] > 0: 11 | cooldown[key] -= 1 12 | time += 1 13 | else: 14 | while cooldown[task] > 0: 15 | for key in cooldown.keys(): #A -> 0, B -> 0 16 | if cooldown[key] > 0: 17 | cooldown[key] -= 1 18 | time += 1 19 | time += 1 20 | time += 1 21 | return time 22 | 23 | 24 | def magicFunc(a = []): 25 | a.append("1") 26 | print(a) 27 | 28 | magicFunc() 29 | magicFunc(["2"]) 30 | 31 | #print(socool(['A', 'A', 'B', 'A', 'B' ], 2)) 32 | #print(socool(['A', 'B', 'B', 'A', 'B' ], 2)) 33 | #print(socool(['A', 'B', 'A', 'C', 'B'], 2)) -------------------------------------------------------------------------------- /Internships/NextCapital/Character Multiple.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | def countCharacters( strings, multiples): 3 | 4 | result = [] 5 | for i in range(len(strings)): 6 | string = strings[i] 7 | multiple = multiples[i] 8 | dictionary = dict() 9 | count = 0 10 | for item in string: 11 | if (dictionary.get(item, -1) == -1): #Not present 12 | dictionary[item] = 1 13 | else: 14 | dictionary[item] = dictionary[item] + 1 15 | 16 | for (k, v) in dictionary.items(): 17 | if (v%multiple == 0): 18 | count = count + 1 19 | result.append(count) 20 | print result 21 | 22 | if __name__=="__main__": 23 | strings = ['aaabbdaaekhfjkcbks', 'askJSKWIUQEBSK'] 24 | multiples = [5, 2] 25 | 26 | print countCharacters(strings, multiples) 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /GeneralPractice/937. Reorder Data in Log Files.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def isdigit(self, char): 6 | if 0 <= ord(char) - ord('0') <= 9: 7 | return True 8 | return False 9 | 10 | def reorderLogFiles(self, logs): 11 | """ 12 | :type logs: List[str] 13 | :rtype: List[str] 14 | """ 15 | digitLog = [] 16 | charLogs = [] 17 | for log in logs: 18 | idx = log.find(' '); 19 | if (self.isdigit(log[idx + 1])): 20 | digitLog.append(log) 21 | else: 22 | charLogs.append(log) 23 | 24 | charLogs = sorted(charLogs) 25 | charLogs.extend(digitLog) 26 | return charLogs 27 | 28 | s=Solution() 29 | print(s.reorderLogFiles(["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"])) 30 | -------------------------------------------------------------------------------- /LeetCodePractice/50. Pow(x, n).py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 300 / 300 test cases passed. 5 | Status: Accepted 6 | Runtime: 39 ms 7 | 8 | Better than : 50% 9 | """ 10 | class Solution(object): 11 | def myPow(self, x, n): 12 | """ 13 | :type x: float 14 | :type n: int 15 | :rtype: float 16 | """ 17 | n_new = n if n >= 0 else -n 18 | res = self.myPowUtil(x, n_new) 19 | if n < 0: 20 | return 1/res 21 | return res 22 | 23 | def myPowUtil(self, x, n): 24 | if n == 0: 25 | return 1 26 | if n == 1: 27 | return x 28 | if n == 2: 29 | return x*x 30 | 31 | if n%2 == 1: 32 | res = self.myPow(x, (n-1)/2) 33 | return x * res * res 34 | else: 35 | res = self.myPow(x, (n)/2) 36 | return res * res -------------------------------------------------------------------------------- /LeetCodePractice/670. Maximum Swap.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def maximumSwap(self, num): 5 | """ 6 | :type num: int 7 | :rtype: int 8 | """ 9 | num = list(str(num)) 10 | 11 | if len(num) in [0, 1]: 12 | return int(''.join(num)) 13 | 14 | old_part = '' 15 | while len(num) > 0: 16 | max_i = num.index(max(num)) 17 | if max_i == 0: 18 | old_part += num[0] 19 | num = num[1:] 20 | continue 21 | 22 | min_i = num.index(min(num[0:max_i])) 23 | num[max_i], num[min_i] = num[min_i], num[max_i] 24 | break 25 | return int(''.join(old_part + ''.join(num))) 26 | 27 | s=Solution() 28 | assert s.maximumSwap(2736) == 7236 29 | assert s.maximumSwap(9973) == 9973 30 | assert s.maximumSwap(98368) == 98863 -------------------------------------------------------------------------------- /GeneralPractice/31. Next Permutation.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def nextPermutation(self, nums): 6 | """ 7 | :type nums: List[int] 8 | :rtype: None Do not return anything, modify nums in-place instead. 9 | """ 10 | 11 | i = len(nums)-1 12 | while i >= 0: 13 | if nums[i] >= nums[i-1]: 14 | i -= 1 15 | else: 16 | break 17 | 18 | if i == -1: 19 | return sorted(nums) 20 | 21 | nums[len(nums) - 1], nums[i] = nums[i], nums[len(nums) - 1] 22 | sorted(nums[i:]) 23 | 24 | return nums 25 | 26 | s=Solution() 27 | print(s.nextPermutation( nums = [1, 2, 3])) 28 | print(s.nextPermutation( nums = [3, 2, 1])) 29 | print(s.nextPermutation( nums = [1, 1, 5])) 30 | print(s.nextPermutation([1])) 31 | print(s.nextPermutation([1,2,8,4,3,7])) 32 | -------------------------------------------------------------------------------- /GeneralPractice/Palindrome subsequence.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution: 5 | 6 | def traverse(self, string): 7 | 8 | idx = -1 9 | result = [] 10 | curr_string = "" 11 | self.traverseUtil(string, idx, result, curr_string) 12 | print(result) 13 | 14 | def traverseUtil(self, string, idx, result, curr_string): 15 | 16 | if idx >= len(string): 17 | return 18 | 19 | result.append(''.join(curr_string)) 20 | 21 | for i in range(idx+1, len(string)): 22 | curr_string += string[i] 23 | print("Beginning string: ", curr_string) 24 | self.traverseUtil(string, i, result, curr_string) 25 | #curr_string.pop() 26 | curr_string = curr_string[:len(curr_string) - 2] # Basically pop the last element. 27 | return 28 | 29 | 30 | s=Solution() 31 | s.traverse("abc") -------------------------------------------------------------------------------- /Internships/Veritas/Rolling Stirng.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def rollingString(s, operations): 5 | s=list(s) 6 | for operation in operations: 7 | leftPtr = int(operation[0]) 8 | rightPtr = int(operation[2]) 9 | operation = operation[4] 10 | 11 | for i in range(leftPtr, rightPtr + 1): 12 | if (operation == 'L'): 13 | if (s[i] == 'a'): 14 | s[i] = 'z' 15 | else: 16 | s[i] = chr(ord(s[i]) - 1) 17 | elif(operation == 'R'): 18 | if (s[i] == 'z'): 19 | s[i] = 'a' 20 | else: 21 | s[i] = chr(ord(s[i]) + 1) 22 | return ''.join(s) 23 | 24 | 25 | if __name__ =="__main__": 26 | print rollingString("abc", ['0 0 L', '2 2 L', '0 2 R']) 27 | print rollingString("abcqusze", ['0 6 L', '1 4 L', '5 7 R']) -------------------------------------------------------------------------------- /LeetCodePractice/Count Complete Tree Nodes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Not all Test cases were working 3 | """ 4 | class TreeNode(object): 5 | def __init__(self, x): 6 | self.val = x 7 | self.left = None 8 | self.right = None 9 | 10 | class Solution(object): 11 | def countNodes(self, root): 12 | if (root is None): 13 | return 0; 14 | tempL= root 15 | tempR = root 16 | heightL = 0 17 | heightR = 0 18 | while(tempL.left is not None): 19 | heightL = heightL + 1 20 | tempL = tempL.left 21 | while (tempR.right is not None): 22 | heightR = heightR + 1 23 | tempL = tempL.right 24 | if ( heightL == heightR): 25 | return (1< n: 14 | n_shift_two = n >> 1 15 | #print n_shift_two 16 | n_res = n ^ n_shift_two 17 | #print " And prod: ", n_res 18 | while n_res: 19 | if (n_res & 1): 20 | n_res = n_res >> 1 21 | else: 22 | return False 23 | return True 24 | 25 | s=Solution() 26 | print s.hasAlternatingBits(4) 27 | print s.hasAlternatingBits(1) 28 | print s.hasAlternatingBits(2) 29 | print s.hasAlternatingBits(5) 30 | print s.hasAlternatingBits(7) 31 | print s.hasAlternatingBits(11) -------------------------------------------------------------------------------- /Leetcode_Challenge/Feb 18/Detect Capital.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | """ 3 | 520 Detect Capital 4 | 5 | 550 / 550 test cases passed. 6 | Status: Accepted 7 | Submitted: 0 minutes ago 8 | """ 9 | 10 | class Solution(object): 11 | def detectCapitalUse(self, word): 12 | """ 13 | :type word: str 14 | :rtype: bool 15 | """ 16 | if (len(word) == 0): 17 | return False 18 | capital = list(filter(lambda x: x.isupper(),word )) 19 | #print " len(capital)", len(capital) 20 | if (len(capital) == len(word)): 21 | return True 22 | if(len(capital) == 1 and word[0].isupper()): 23 | return True 24 | if (len(capital) ==0): 25 | return True 26 | return False 27 | 28 | 29 | s=Solution() 30 | print s.detectCapitalUse("USA") 31 | print s.detectCapitalUse("FlaG") 32 | print s.detectCapitalUse("Leetcode") #Expected true -------------------------------------------------------------------------------- /GeneralPractice/15. 3Sum.py: -------------------------------------------------------------------------------- 1 | from typing import List, Set 2 | 3 | 4 | class Solution: 5 | def threeSum(self, nums: List[int]) -> set[str]: 6 | map = set() 7 | nums = sorted(nums) 8 | for i in range(len(nums)-2): 9 | if i > 0 and nums[i-1] == nums[i]: 10 | continue 11 | left = i + 1 12 | right = len(nums)-1 13 | 14 | while left < right: 15 | if nums[left] + nums[i] + nums[right] == 0: 16 | key = str(nums[i]) + '#' + str(nums[left]) + '#' + str(nums[right]) 17 | print(key) 18 | map.add(key) 19 | left += 1 20 | elif nums[left] + nums[i] + nums[right] < 0: 21 | left += 1 22 | else: 23 | right -=1 24 | return map 25 | 26 | s=Solution() 27 | print(s.threeSum(nums = [-1,0,1,2,-1,-4])) -------------------------------------------------------------------------------- /Internships/Formlabs_serverCode.py: -------------------------------------------------------------------------------- 1 | # Enter your code here. Read input from STDIN. Print output to STDOUT 2 | from threading import Event, Thread, Timer 3 | import random 4 | 5 | data = [] 6 | data_to_get=10 7 | 8 | class Server: 9 | def getData(self, callback, event): 10 | self.cb = callback 11 | self.event=event 12 | self.t = Timer(0.0005, self.dataReady) 13 | self.t.start() 14 | 15 | def dataReady(self): 16 | self.cb(random.random()) 17 | self.event.set() 18 | 19 | 20 | def ready(d): 21 | data.append(d) 22 | 23 | def done(): 24 | print data 25 | 26 | def getData(): 27 | theServer=Server() 28 | 29 | for i in range(data_to_get): 30 | event = Event() 31 | theServer.getData(ready, event) 32 | event.wait() 33 | 34 | done() 35 | 36 | def someFunctionInsideMainThread(): 37 | thread=Thread(target=getData) 38 | thread.start() -------------------------------------------------------------------------------- /Internships/LiveRamp/Monkey.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is the question which was actually asked in LiveRamp coding challenge. 3 | """ 4 | def solution(A, D): 5 | dest = len(A) # this is N 6 | curr = -1 7 | 8 | if (D > dest): 9 | return 0 10 | for time in range(0, max(A)+1): 11 | if (time in A): #this will filter -1 12 | #find the stone position which is now visible 13 | stone = A.index(time) 14 | if (curr == -1 and stone <= D): 15 | curr = stone 16 | elif (stone <= curr): 17 | continue #No point of this stone 18 | elif (stone-curr <= D): #forgot to add in the main solution 19 | curr = stone 20 | if (dest - curr <= D): 21 | return time 22 | else: 23 | continue; 24 | return -1 25 | 26 | 27 | if __name__ =="__main__": 28 | print solution([1, -1, 0, 7, 3, 6, 8, 11, 18], 3) -------------------------------------------------------------------------------- /LeetCodePractice/42. Trapping Rain Water.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def trap(self, height): 5 | """ 6 | :type height: List[int] 7 | :rtype: int 8 | """ 9 | 10 | maxheight = max(height) 11 | leftMax = height[0] 12 | water = 0 13 | for i in range(2, height.index(maxheight)): 14 | res = (min(leftMax, maxheight) - height[i]) 15 | water = water + res if res >= 0 else 0 16 | leftMax = max(leftMax, height[i]) 17 | 18 | leftMax = height[len(height) - 1] 19 | for i in range(len(height) - 1, height.index(maxheight), -1): 20 | res = (min(leftMax, maxheight) - height[i]) 21 | water = water + res if res >= 0 else 0 22 | leftMax = max(leftMax, height[i]) 23 | 24 | return water 25 | 26 | s=Solution() 27 | print s.trap([0,1,0,2,1,0,1,3,2,1,2,1]) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /LeetCodePractice/Search a 2D Matrix II.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 127 / 127 test cases passed. 4 | Status: Accepted 5 | Runtime: 112 ms 6 | """ 7 | 8 | class Solution(object): 9 | def searchMatrix(self, matrix, target): 10 | """ 11 | :type matrix: List[List[int]] 12 | :type target: int 13 | :rtype: bool 14 | """ 15 | i=0 16 | j=len(matrix[0]) - 1 17 | 18 | while (i < len(matrix) and j >= 0): 19 | if (matrix[i][j] == target): 20 | return True 21 | if (matrix[i][j] > target): 22 | j = j - 1 23 | else: 24 | i = i + 1 25 | return False 26 | 27 | 28 | s=Solution() 29 | matrix=[ 30 | [1, 4, 7, 11, 15], 31 | [2, 5, 8, 12, 19], 32 | [3, 6, 9, 16, 22], 33 | [10, 13, 14, 17, 24], 34 | [18, 21, 23, 26, 30] 35 | ] 36 | print s.searchMatrix(matrix, 5) 37 | print s.searchMatrix(matrix, 31) 38 | 39 | -------------------------------------------------------------------------------- /Internships/LiveRamp/BFS.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Liveramp qs taken from online source. However, I was not asked any question as mentioned on glassdoor 4 | """ 5 | def bfs(graph, start, end): 6 | queue = [[start]] 7 | while queue: 8 | path = queue.pop(0) 9 | node = path[0] 10 | 11 | for item in graph[node] - set(path): 12 | print "Exploring for item", item 13 | new_path = [item] 14 | new_path += path 15 | queue.append(new_path) 16 | print "Appending" , new_path 17 | if (item == end): 18 | return "Length = " + str(len(new_path)) + " PATH = " + str(new_path) 19 | 20 | 21 | if __name__=="__main__": 22 | graph = {'A': set(['B', 'C']), 23 | 'B': set(['A', 'D', 'E']), 24 | 'C': set(['A', 'F']), 25 | 'D': set(['B']), 26 | 'E': set(['B', 'F']), 27 | 'F': set(['C', 'E'])} 28 | print bfs(graph, 'A', 'E') -------------------------------------------------------------------------------- /LeetCodePractice/673. Number of Longest Increasing Subsequence.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def findNumberOfLIS(self, arr): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | n = len(arr) 10 | 11 | # Declare the list (array) for LIS and initialize LIS 12 | # values for all indexes 13 | lis = [1]*n 14 | 15 | # Compute optimized LIS values in bottom up manner 16 | for i in range (1 , n): 17 | for j in range(0 , i): 18 | if arr[i] > arr[j] and lis[i] < lis[j] + 1 : 19 | lis[i] = lis[j]+1 20 | print lis 21 | maxEle = max(lis) 22 | NumOfMax = list(filter(lambda x: x == maxEle, lis)) 23 | print "NumOfMax: ", NumOfMax 24 | return len(NumOfMax) 25 | 26 | s=Solution() 27 | #print s.findNumberOfLIS([1,3,5,4,7]) 28 | print s.findNumberOfLIS([2,2,2,2,2]) -------------------------------------------------------------------------------- /LeetCodePractice/98. Validate Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | 98. Validate Binary Search Tree 3 | 4 | 74 / 74 test cases passed. 5 | Status: Accepted 6 | Runtime: 92 ms 7 | """ 8 | 9 | import sys 10 | # Definition for a binary tree node. 11 | # class TreeNode(object): 12 | # def __init__(self, x): 13 | # self.val = x 14 | # self.left = None 15 | # self.right = None 16 | 17 | class Solution(object): 18 | def isValidBSTUtil(self, root, max_val, min_val): 19 | if (root is None): 20 | return True 21 | if (root.val > max_val or root.val < min_val): 22 | return False 23 | return self.isValidBSTUtil(root.left, root.val - 1, min_val) and self.isValidBSTUtil(root.right, max_val, root.val + 1) 24 | def isValidBST(self, root): 25 | """ 26 | :type root: TreeNode 27 | :rtype: bool 28 | """ 29 | return self.isValidBSTUtil(root, sys.maxint, -sys.maxint) -------------------------------------------------------------------------------- /Internships/Aetion/ArithmeticSequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Find maximum substring such that it is in AP 3 | """ 4 | 5 | 6 | def solution(A): 7 | start = 0 8 | end = 1 9 | result = 0 10 | while(start < len(A)): 11 | while(end + 1 < len(A) and (A[end] - A[end-1] == A[end+1] - A[end])): 12 | end = end + 1 13 | if (end - start == 2): 14 | #print " Found at start = ", start , " and end = ", end 15 | result = result + 1 16 | elif (end - start > 2): 17 | #print " Found at start = ", start , " and end = ", end 18 | result = result + 2 * (end - start - 2) + 1 19 | if ( result > 10**9): 20 | return -1 21 | #print " New result = ", result 22 | start = end 23 | end = end + 1 24 | return result 25 | 26 | 27 | if __name__=="__main__": 28 | print solution([-1, 1, 3, 3, 3, 2, 1, 0] ) 29 | print solution([-2, 4, 2, 0] ) -------------------------------------------------------------------------------- /Internships/Delete and Earn - VMWARE.py: -------------------------------------------------------------------------------- 1 | # Complete the function below. 2 | # 8 pass of 14 some had time exception 3 | 4 | """ 5 | you have to maximumize points such that when when u burst ai ai - 1 and ai + 1 are automatically burst. 6 | Now by bursting such ai gather points. 7 | Second idea could have been sorting in descending order. Burst first one. while next elements are ai + 1 then ignore that. 8 | My assumption is correct solution is greedy but cann't be sure. 9 | """ 10 | def maxPoints(elements): 11 | 12 | result = 0 13 | while(len(elements) > 0): 14 | max_iteration = max(elements) 15 | 16 | elements.remove(max_iteration) 17 | elements = list(filter(lambda x: x != max_iteration + 1 , elements)) 18 | elements = list(filter(lambda x: x != max_iteration - 1 , elements)) 19 | result = result + max_iteration 20 | return result 21 | 22 | maxPoints([1, 2, 1, 3, 2, 3]) 23 | maxPoints([3, 3, 4, 2]) 24 | 25 | -------------------------------------------------------------------------------- /LeetCodePractice/Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | """ 2 | 217. Contains Duplicate 3 | 17 / 17 test cases passed. 4 | Status: Accepted 5 | Runtime: 69 ms 6 | """ 7 | class Solution(object): 8 | """ 9 | Cannot handle negative numbers 10 | """ 11 | def containsDuplicate1(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: bool 15 | """ 16 | counter=0 17 | for item in nums: 18 | if ( counter & 1< 0): 19 | return True 20 | counter = counter | 1< 1): 10 | start = save + 5 11 | save = start 12 | for j in range(5): 13 | if (j == 1): 14 | start = start + gap 15 | grid[i][j] = start % 50 if start % 50 != 0 else 50 16 | start = start + 1 17 | print customDisplayGrid2(grid) 18 | 19 | def customDisplayGrid2(grid): 20 | line = '' 21 | for row in grid: 22 | line += ', '.join(str(x) for x in row) 23 | line += '\n' 24 | return line 25 | 26 | 27 | if __name__ == "__main__": 28 | grid = [[ 0 for i in range(5)] for j in range(10)] 29 | gap = 0 30 | for i in range(10): 31 | print "For week: ", i + 1 32 | display(gap) 33 | gap = gap + 5 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /GeneralPractice/41. First Missing Positive.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Runtime: 24 ms, faster than 60.56% of Python online submissions for First Missing Positive. 5 | Memory Usage: 13.5 MB, less than 34.61% of Python online submissions for First Missing Positive. 6 | 7 | """ 8 | class Solution: 9 | def firstMissingPositive(self, nums): 10 | 11 | constant = len(nums) + 100 12 | 13 | for i in range(len(nums)): 14 | if nums[i] <= 0: 15 | nums[i] = constant 16 | 17 | for i in range(len(nums)): 18 | idx = abs(nums[i]) 19 | if (idx < len(nums) + 1) and (nums[idx - 1] > 0): 20 | nums[idx - 1] *= -1 21 | 22 | res = len(nums) + 1 23 | for i in range(len(nums)): 24 | if nums[i] > 0: 25 | res = i + 1 26 | break 27 | 28 | return res 29 | 30 | s=Solution() 31 | print(s.firstMissingPositive([3, 4, -4, -8])) -------------------------------------------------------------------------------- /LeetCodePractice/Group Anagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | 49. Group Anagrams 3 | 4 | 100 / 100 test cases passed. 5 | Status: Accepted 6 | Runtime: 289 ms 7 | """ 8 | class Solution(object): 9 | def groupAnagrams(self, strs): 10 | """ 11 | :type strs: List[str] 12 | :rtype: List[List[str]] 13 | """ 14 | anagrams=dict() 15 | #print type(anagrams) 16 | for item in strs: 17 | temp=sorted(item) 18 | temp=''.join(temp) 19 | if (anagrams.get(temp, -1) == -1): 20 | anagrams[temp]=list() 21 | anagrams[temp].append(item) 22 | #print anagrams 23 | 24 | result=[] 25 | for (k,v) in anagrams.items(): 26 | sorted(v) 27 | result.append(sorted(v)) 28 | #anagrams[k] = sorted(v) 29 | result=sorted(result) 30 | return result 31 | s=Solution() 32 | print s.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) -------------------------------------------------------------------------------- /LeetCodePractice/442. Find All Duplicates in an Array.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 28 / 28 test cases passed. 5 | Status: Accepted 6 | Runtime: 356 ms 7 | 8 | Beats 30% submission. Also x in arr is a heavy operation 9 | """ 10 | class Solution(object): 11 | def findDuplicates(self, nums): 12 | """ 13 | :type nums: List[int] 14 | :rtype: List[int] 15 | """ 16 | result = [] 17 | for i in range(len(nums)): 18 | index = nums[i] - 1 if nums[i] > 0 else -nums[i] - 1 19 | #print "IndeX: ", index 20 | if nums[index] < 0: 21 | # print "At index: ", index 22 | number = nums[i] if nums[i] > 0 else -nums[i] 23 | if number not in result: 24 | result.append(number) 25 | else: 26 | nums[index] = -nums[index] 27 | return result 28 | 29 | s=Solution() 30 | print s.findDuplicates([4,3,2,7,8,2,3,1]) 31 | -------------------------------------------------------------------------------- /CompaniesHiringQuestions/MicrosoftCoding_Order.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Microsoft coding challenge 4 | """ 5 | def doItAgian(lines): 6 | N = int(lines[0]) 7 | count = 1 8 | lost = [] 9 | for item in lines[1:]: 10 | s_ = filter(lambda c: c == 'W', line) 11 | if (len(s_) == 0): 12 | lost.append(count) 13 | 14 | if __name__=="__main__": 15 | lines = [line.rstrip('\r\n') for line in open('/Users/deepika/Desktop/MicrosoftExam/_4/PracticeInput.txt')] 16 | 17 | print lines 18 | #doItAgian(lines) 19 | N = int(lines[0]) 20 | #print N 21 | trueMapping = dict() 22 | count = 1; 23 | for line in lines[1:]: 24 | s_ = filter(lambda c: c == 'W', line) 25 | trueMapping[count] = len(s_) 26 | count = count + 1 27 | 28 | print trueMapping 29 | result = [] 30 | for w in sorted(trueMapping, key=trueMapping.get, reverse=True): 31 | result.append(str(w)) 32 | 33 | print ' '.join(result) 34 | 35 | -------------------------------------------------------------------------------- /HackerRankProblems/Birthday Chocolate.py: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | import sys 4 | 5 | 6 | n = int(raw_input().strip()) 7 | squares = map(int, raw_input().strip().split(' ')) 8 | d,m = raw_input().strip().split(' ') 9 | d,m = [int(d),int(m)] # m is the number of squares and d is total sum which we need 10 | # your code goes here 11 | 12 | if (len(squares) < m): 13 | print "0" 14 | else: 15 | result = 0 16 | firstM_sum = 0 17 | for i in range(0, m): 18 | firstM_sum = firstM_sum + squares[i] 19 | 20 | #print " initially sum = ", firstM_sum 21 | if (firstM_sum == d): 22 | result = result + 1 23 | for i in range(1,len(squares) - m + 1): 24 | 25 | firstM_sum = firstM_sum - squares[i-1] 26 | firstM_sum = firstM_sum + squares[m-1+i] 27 | #print " Will sum from i = ", i, " till last = ", i + m-1, " with sum = ", firstM_sum 28 | if (firstM_sum == d): 29 | result = result + 1 30 | print result 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /LeetCodePractice/387. First Unique Character in a String.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 104 / 104 test cases passed. 5 | Status: Accepted 6 | Runtime: 212 ms 7 | """ 8 | class Solution(object): 9 | def firstUniqChar(self, s): 10 | """ 11 | :type s: str 12 | :rtype: int 13 | """ 14 | 15 | queue = list() 16 | seenSet = set() 17 | 18 | for i in range(len(s)): 19 | _char = s[i] 20 | if _char not in seenSet: 21 | queue.append(_char) 22 | seenSet.add(_char) 23 | elif _char in seenSet: 24 | if _char in queue: 25 | queue.remove(_char) 26 | else: 27 | continue 28 | if len(queue) == 0: 29 | return -1 30 | popped = queue.pop(0) 31 | return s.find(popped) 32 | 33 | s=Solution() 34 | print s.firstUniqChar("leetcode") 35 | print s.firstUniqChar("loveleetcode") 36 | -------------------------------------------------------------------------------- /LeetCodePractice/11. Container With Most Water.py: -------------------------------------------------------------------------------- 1 | # This question is different that FB question 2 | """ 3 | 49 / 49 test cases passed. 4 | Status: Accepted 5 | Runtime: 72 ms 6 | """ 7 | class Solution(object): 8 | 9 | def maxArea(self, height): 10 | """ 11 | :type height: List[int] 12 | :rtype: int 13 | """ 14 | left = 0 15 | right = len(height) - 1 16 | maxWater = 0 17 | while(left < right): 18 | maxWater = max(maxWater, min(height[left], height[right])* (right - left)) 19 | if (height[left] < height[right]): 20 | left = left + 1 21 | else: 22 | right = right - 1 23 | return maxWater 24 | 25 | s=Solution() 26 | print s.maxArea([1, 2, 3, 4, 5]) 27 | print s.maxArea([5, 4, 3, 2, 1]) 28 | #print s.maxArea([5, 4, 30, 12, 11]) 29 | print s.maxArea([1, 1]) 30 | print s.maxArea([1, 2, 1]) 31 | print s.maxArea([1,2,4,3]) #expected 4 32 | print s.maxArea([2,3,10,5,7,8,9]) 33 | -------------------------------------------------------------------------------- /Leetcode_Challenge/Oct 8/Partition Equal Subset Sum.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Not exactly the solution, 4 | This will be solved using DFS 5 | """ 6 | class Solution(object): 7 | def canPartition(self, nums): 8 | nums = sorted(nums) 9 | left = 0 10 | right = len(nums) - 1 11 | 12 | sumR = nums[right] 13 | sumL = nums[left] 14 | 15 | elementCovered = 2 16 | while(left < right): 17 | if (sumR == sumL and elementCovered == len(nums)): 18 | return True 19 | elif (sumR > sumL): 20 | left = left + 1 21 | sumL = sumL + nums[left] 22 | else: 23 | right = right - 1 24 | sumR = sumR + nums[right] 25 | elementCovered = elementCovered + 1 26 | return False 27 | 28 | 29 | if __name__ == "__main__": 30 | _s = Solution() 31 | s = [1, 2, 3, 5] 32 | print _s.canPartition(s) 33 | s = [1, 5, 11, 5] 34 | print _s.canPartition(s) -------------------------------------------------------------------------------- /CompaniesHiringQuestions/MicrosoftCoding_SecretDecoder.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Microsoft coding challenge 4 | Accepted Solution 5 | """ 6 | 7 | if __name__=="__main__": 8 | mapping = raw_input('') 9 | line = raw_input('') 10 | mappings = mapping.split() 11 | trueMapping = {}; 12 | for item in mappings: 13 | splitItem = map(lambda c: c.upper(), item) 14 | trueMapping[splitItem[0]] = splitItem[2] 15 | 16 | print trueMapping 17 | 18 | result = '' 19 | for item in line: 20 | if ord(item) >= 65 and ord(item) <= 90: #Uppercase 21 | if (trueMapping.get(item, -1) != -1): 22 | result = result + trueMapping.get(item) 23 | elif (ord(item) >= 97 and ord(item) <= 122): #encountered lower case 24 | itemUpper = item.upper() 25 | if (trueMapping.get(itemUpper, -1) != -1): 26 | result = result + trueMapping.get(itemUpper).lower() 27 | else: 28 | result = result + item; 29 | 30 | print result -------------------------------------------------------------------------------- /LeetCodePractice/676. Implement Magic Dictionary.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | class MagicDictionary(object): 3 | 4 | def __init__(self): 5 | """ 6 | Initialize your data structure here. 7 | """ 8 | self.EntireSet = [] 9 | 10 | 11 | 12 | def buildDict(self, dict): 13 | """ 14 | Build a dictionary through a list of words 15 | :type dict: List[str] 16 | :rtype: void 17 | """ 18 | for x in dict: 19 | self.EntireSet.append(x) 20 | print self.EntireSet 21 | 22 | 23 | 24 | def search(self, word): 25 | """ 26 | Returns if there is any word in the trie that equals to the given word after modifying exactly one character 27 | :type word: str 28 | :rtype: bool 29 | """ 30 | 31 | 32 | 33 | 34 | # Your MagicDictionary object will be instantiated and called as such: 35 | obj = MagicDictionary() 36 | obj.buildDict(["hello", "leetcode"]) 37 | # param_2 = obj.search(word) -------------------------------------------------------------------------------- /LeetCodePractice/682. Baseball Game.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | class Solution(object): 3 | def calPoints(self, ops): 4 | """ 5 | :type ops: List[str] 6 | :rtype: int 7 | """ 8 | stack = [] 9 | for op in ops: 10 | if op not in ["C","D","+"]: 11 | stack.append(int(op)) 12 | else: 13 | if op == "C": 14 | stack.pop() 15 | elif op == "D": 16 | lastElement = stack[-1] 17 | stack.append(lastElement * 2) 18 | elif op == "+": 19 | last1 = stack[-1] 20 | last2 = stack[-2] 21 | stack.append(last1 + last2) 22 | else: 23 | print "Received something unusual: ", op 24 | return sum(stack) 25 | 26 | s=Solution() 27 | assert s.calPoints(["5","2","C","D","+"]) == 30 28 | assert s.calPoints(["5","-2","4","C","D","9","+","+"]) == 27 29 | 30 | -------------------------------------------------------------------------------- /AlphaBeta/Tic Tac toe/README.md: -------------------------------------------------------------------------------- 1 | This code is the extension over Basic AlphaBeta algorithm. 2 | In the basic version value was used in the terminal node however in this case we not only need the value 3 | but also we need the board states to be sent towards to root. 4 | 5 | Hence the extra condition on line number 115 and 127 6 | 7 | I have used to even or odd depth to find if the turn is to maximize or to minimize the game 8 | 9 | custom_print is used to print all the children clearly in three lines all separated by pipe symbol. 10 | 11 | No extenral dependency in this case. Just use 12 | >python Tic Tac Toe.py 13 | 14 | To see the debugging path uncomment all print statements. 15 | 16 | Here is the description of the problem statement. 17 | https://www.hackerearth.com/practice/algorithms/string-algorithm/manachars-algorithm/practice-problems/multiplayer/tic-tac-toe/description/ 18 | 19 | I played the bot against many random users and the CTO of hackereath. 20 | Screenshot are there for reference. 21 | 22 | 23 | -------------------------------------------------------------------------------- /LeetCodePractice/167. Two Sum II - Input array is sorted.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, numbers, target): 3 | """ 4 | :type numbers: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | result = [] 9 | if (len(numbers) == 1): 10 | result.append(0) 11 | result.append(0) 12 | return result 13 | left=0 14 | right=len(numbers)-1 15 | while(left < right): 16 | if (numbers[left] + numbers[right] == target): 17 | result =[] 18 | result.append(left + 1) 19 | result.append(right + 1) 20 | return result 21 | if (numbers[left] + numbers[right] < target): 22 | left = left + 1 23 | else: 24 | right = right - 1 25 | result.append(0) 26 | result.append(0) 27 | return result 28 | 29 | s=Solution() 30 | print s.twoSum([2, 7, 11, 15], target=9) 31 | -------------------------------------------------------------------------------- /GeneralPractice/Football_score.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | import copy 3 | 4 | POINT_VALUES = [2, 3, 7] 5 | def footballScores(score): 6 | # initialize the table with the ways to score 0 points 7 | T = { 0: [{}] } 8 | for k in range(1, score + 1): 9 | T[k] = [] 10 | for value in POINT_VALUES: 11 | if k - value < 0 or k - value not in T: 12 | # if we can't fit this point value, skip it 13 | continue 14 | 15 | for score_config in T[k - value]: 16 | # for each score config in the previous total, append this value to it 17 | new_score_config = copy.copy(score_config) 18 | new_score_config[value] = new_score_config.get(value, 0) + 1 19 | 20 | if new_score_config not in T[k]: 21 | # if we haven't already seen this config, add it 22 | T[k].append(new_score_config) 23 | 24 | return T[score] 25 | 26 | print footballScores(10) #How many ways can we form 10. Same as coin change problem -------------------------------------------------------------------------------- /Internships/Google/StringManipulation.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | There are licence keys such as A-BCDEF-GEF. Given K you have to return string such .....-FED-GEF 4 | First group may have less than k elements but each other group should have k elements 5 | """ 6 | def solution(S, K): 7 | result = [] 8 | i = len(S) - 1 9 | 10 | slice = K 11 | while (i >= 0): 12 | part = [] 13 | while (slice > 0 and i >= 0): 14 | if (ord(S[i]) != ord('-') ): 15 | part.insert(0, (S[i].upper())) 16 | slice = slice - 1 17 | i = i - 1 18 | else: 19 | i = i - 1 20 | slice = K 21 | result.insert(0, (''.join(part))) 22 | #result = reversed(result) 23 | return '-'.join(result) 24 | 25 | if __name__ == "__main__": 26 | S = "2-4A0r7-4k" 27 | K = 3 28 | print solution(S, K) 29 | 30 | K=4 31 | print solution(S, K) 32 | 33 | K=2 34 | print solution(S, K) 35 | 36 | S="r" 37 | K=1 38 | print solution(S, K) -------------------------------------------------------------------------------- /LeetCodePractice/LONGEST CONSECUTIVE SEQUENCE.py: -------------------------------------------------------------------------------- 1 | """ 2 | 67 / 67 test cases passed. 3 | Status: Accepted 4 | Runtime: 79 ms 5 | """ 6 | class Solution(object): 7 | def longestConsecutive(self, nums): 8 | """ 9 | :type nums: List[int] 10 | :rtype: int 11 | """ 12 | setNums=set() 13 | for item in nums: 14 | setNums.add(item) 15 | 16 | max_of_now = -1 17 | while setNums: 18 | count = 1 19 | target = setNums.pop() 20 | left, right = target - 1, target + 1 21 | while left in setNums: 22 | setNums.remove(left) 23 | count = count + 1 24 | left = left - 1 25 | while right in setNums: 26 | setNums.remove(right) 27 | count = count + 1 28 | right = right + 1 29 | max_of_now = max(max_of_now, count) 30 | return max_of_now 31 | 32 | 33 | 34 | s=Solution() 35 | print s.longestConsecutive([100, 4, 200, 1, 3, 2]) -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Zappos_FormMinNumber.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | """ 4 | 402. Remove K Digits 5 | 6 | Also 7 | Zappos Coding challenge 8 | given a number in string format say something ike 1234089389 and number n = number of elements u can delete 9 | find the smallest possible number you can make out of these. 10 | """ 11 | def attempt2(s, n): 12 | N = len(s) 13 | targetLen = N - n 14 | result = '' 15 | while(targetLen != 0): 16 | min_so_far = min(s[0:n+1]) 17 | result = result + min_so_far 18 | s = s[s.index(min_so_far) + 1 :] 19 | targetLen = targetLen - 1 20 | n = len(s) - targetLen 21 | i = 0 22 | while(i < len(result) and ord(result[i]) == ord('0')): 23 | i = i + 1 24 | if (len(result[i:]) == 0): 25 | return "0" 26 | else: 27 | return result[i:] 28 | 29 | if __name__=="__main__": 30 | s = "1234089389"; 31 | n = 4 32 | if (n >= len(s)): 33 | print "0" 34 | elif (n == 0): 35 | print s 36 | else: 37 | print attempt2(s, n) -------------------------------------------------------------------------------- /LeetCodePractice/266. Palindrome Permutation.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Given a string, determine if a permutation of the string could form a palindrome. 5 | 6 | For example, 7 | "code" -> False, "aab" -> True, "carerac" -> True. 8 | 9 | 26 / 26 test cases passed. 10 | Status: Accepted 11 | Runtime: 32 ms 12 | 13 | About 60% better 14 | """ 15 | class Solution(object): 16 | def canPermutePalindrome(self, s): 17 | """ 18 | :type s: str 19 | :rtype: bool 20 | """ 21 | dictionary = dict() 22 | for _s in s: 23 | if _s in dictionary: 24 | dictionary[_s] = dictionary[_s] + 1 25 | else: 26 | dictionary[_s] = 1 27 | 28 | foundOdd = False 29 | for k, v in dictionary.items(): 30 | if v % 2 == 0: 31 | continue 32 | else: 33 | if foundOdd: 34 | return False 35 | foundOdd = True 36 | continue 37 | return True 38 | 39 | -------------------------------------------------------------------------------- /Codility.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def shortestWinterLength(listofTemperatures): 5 | 6 | if len(listofTemperatures) == 0 : 7 | return 0 8 | 9 | length = len(listofTemperatures) 10 | winter_high = listofTemperatures[0] 11 | overall_high = listofTemperatures[0] 12 | winter_length = 0 13 | 14 | # Get max in the left array 15 | for temperature in listofTemperatures: 16 | if temperature <= winter_high : 17 | winter_high = overall_high 18 | elif temperature > overall_high : 19 | overall_high = temperature 20 | print("winter_high = " + str(winter_high) + " overall_high = " + str(overall_high)) 21 | 22 | # count all the values which are less than max in left array 23 | for temperature in listofTemperatures : 24 | if temperature <= winter_high : 25 | winter_length += 1 26 | 27 | # total length of the left array 28 | print (winter_length) 29 | 30 | shortestWinterLength([5, -2, 3, 8, 6]) 31 | shortestWinterLength([-5, -5, -5, -42, 6, 12]) -------------------------------------------------------------------------------- /GeneralPractice/680. Valid Palindrome II.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def isPal(self, s, left, right): 5 | 6 | while (left < len(s) and right >= 0 and s[left] == s[right]): 7 | left += 1 8 | right -= 1 9 | return left >= right 10 | 11 | def validPalindrome(self, s): 12 | """ 13 | :type s: str 14 | :rtype: bool 15 | """ 16 | left = 0 17 | right = len(s) - 1 18 | deleteChar = 0 19 | while (left < len(s) and right >= 0 and left <= right): 20 | if (s[left] == s[right]): 21 | left += 1 22 | right -= 1 23 | else: 24 | if (self.isPal(s, left, right - 1)): 25 | return True 26 | if (self.isPal(s, left + 1, right)): 27 | return True 28 | return False 29 | return True 30 | 31 | 32 | 33 | 34 | s=Solution() 35 | 36 | print(s.validPalindrome("aba")) 37 | print(s.validPalindrome("abca")) 38 | -------------------------------------------------------------------------------- /GeneralPractice/5561. Get Maximum in Generated Array.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Submitted: Success 5 | """ 6 | 7 | class Solution(object): 8 | def getMaximumGenerated(self, n): 9 | """ 10 | :type n: int 11 | :rtype: int 12 | """ 13 | 14 | if n == 0: 15 | return 0 16 | if n == 1: 17 | return 1; 18 | if n == 2: 19 | return 1 20 | 21 | arr = [ 0 for i in range(n+1)] 22 | arr[0] = 0 23 | arr[1] = 1 24 | 25 | max_so_far = 1 26 | 27 | for i in range(2, n+1): 28 | if i % 2 == 0: 29 | arr[i] = arr[i/2] 30 | else: 31 | arr[i] = arr[i-1] + arr[i/2 + 1] 32 | max_so_far = max(max_so_far, arr[i]) 33 | # print(arr) 34 | return max_so_far 35 | s=Solution() 36 | print(s.getMaximumGenerated(0)) 37 | print(s.getMaximumGenerated(1)) 38 | print(s.getMaximumGenerated(2)) 39 | print(s.getMaximumGenerated(3)) 40 | print(s.getMaximumGenerated(7)) 41 | #[0,1,1,2,1,3,2,3] -------------------------------------------------------------------------------- /GeneralPractice/contact_dedup.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | contacts = { 3 | "C1" : ["E1", "E2"], 4 | "C2" : ["E3"], 5 | "C3" : ["E2", "E4"], 6 | "C4" : ["E4"], 7 | "C5" : ["E3"], 8 | "C6" : ["E5"] 9 | } 10 | 11 | def dfs(edges, contact, seen, found=None): 12 | found = found or [] 13 | if contact not in seen: 14 | seen.add(contact) 15 | found.append(contact) 16 | emails = contacts[contact] 17 | for email in emails: 18 | for other in edges[email]: 19 | dfs(edges, other, seen, found) 20 | 21 | return found 22 | 23 | def deduplication(contacts): 24 | by_email = {} 25 | for contact in contacts: 26 | emails = contacts[contact] 27 | for email in emails: 28 | if email not in by_email: 29 | by_email[email] = [] 30 | by_email[email].append(contact) 31 | 32 | print("by_email : ", by_email) 33 | 34 | 35 | seen = set() 36 | print filter(None, [dfs(by_email, contact, seen) for contact in contacts]); 37 | 38 | 39 | deduplication(contacts) -------------------------------------------------------------------------------- /Internships/Bloomberg/License to Hack.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | if __name__ == "__main__": 4 | line = raw_input('') 5 | N = int(raw_input('')) 6 | 7 | toggle = True 8 | i = 0 9 | 10 | result = [] 11 | if ( N == 1): 12 | print line 13 | elif ( N > len(line)): 14 | print line[::-1] 15 | else: 16 | while (i < len(line)): 17 | if (toggle): 18 | start = i 19 | end = i + N-1 20 | portion = list(line[start:end + 1]) 21 | portion.reverse() 22 | reverse = "".join(portion) 23 | #print "start = ", start, " end = ", end 24 | result.append(reverse) 25 | toggle = False 26 | i = i + N 27 | else: 28 | start = i 29 | end = i + N - 1 30 | toggle = True 31 | #print "start = ", start, " end = ", end 32 | result.append(line[start:end + 1]) 33 | i = i + N 34 | 35 | #print result 36 | print "".join(result) -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Twitter1.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | def findMutationDistance(start, end, bank): 4 | 5 | def isviable(current, string): 6 | diff = 0 7 | for i in range(len(current)): 8 | if current[i] != string[i]: 9 | diff = diff + 1 10 | return diff == 1 11 | 12 | queue = [] 13 | visited = set() 14 | queue.append([start, start , 0]) 15 | visited.add(start) 16 | results = [start] 17 | while queue: 18 | current, previous, steps = queue.pop() 19 | 20 | if current == end: 21 | print results 22 | return steps 23 | 24 | for string in bank: 25 | if string not in visited and isviable(current, string) and string != previous: 26 | results.append(string) 27 | 28 | visited.add(string) 29 | queue.append([string, current, steps + 1]) 30 | 31 | assert findMutationDistance("AACCGGTT", "AACCGGTA", ["AACCGGTA"]) == 1 32 | assert findMutationDistance("AAAAACCC", "AACCCCCC", ["AAAACCCC", "AAACCCCC", "AACCCCCC"]) == 3 -------------------------------------------------------------------------------- /Leetcode_Challenge/Oct 15/Longest Repeating Character Replacement.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. 4 | Find the length of a longest substring containing all repeating letters you can get after performing the above operations. 5 | 6 | Note: 7 | Both the string's length and k will not exceed 104. 8 | """ 9 | class Solution(object): 10 | def characterReplacement(self, s, k): 11 | """ 12 | :type s: str 13 | :type k: int 14 | :rtype: int 15 | """ 16 | #find character with max occurence 17 | character = dict() 18 | max = 0 19 | for i in s: 20 | if (character.get(i, -1) == -1): 21 | character[i] = 1 22 | else: 23 | character[i] = character[i] + 1 24 | if (character[i] > max): 25 | max = character[i] 26 | 27 | if __name__ == "__main__": 28 | sol = Solution() 29 | sol.characterReplacement("ABAB", 2) 30 | sol.characterReplacement("AABABBA", 1) 31 | -------------------------------------------------------------------------------- /GeneralPractice/1047. Remove All Adjacent Duplicates In String.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Runtime: 116 ms, faster than 30.05% of Python online submissions for Remove All Adjacent Duplicates In String. 5 | Memory Usage: 13.2 MB, less than 55.16% of Python online submissions for Remove All Adjacent Duplicates In String. 6 | """ 7 | 8 | class Solution(object): 9 | def removeDuplicates(self, S): 10 | """ 11 | :type S: str 12 | :rtype: str 13 | """ 14 | 15 | 16 | if len(S) == 0 or len(S) == 1: 17 | return S 18 | 19 | stack = [] 20 | 21 | i = 0 22 | while i < len(S): 23 | 24 | if len(stack) == 0 or stack[-1] != S[i]: 25 | stack.append(S[i]) 26 | 27 | 28 | elif len(stack) > 0 and stack[-1] == S[i]: 29 | saved = S[i] 30 | 31 | while len(stack) > 0 and stack[-1] == saved: 32 | stack.pop() 33 | # don't handle the look ahead in this problem. Unlike candy crush 34 | i += 1 35 | 36 | 37 | 38 | return ''.join(stack) -------------------------------------------------------------------------------- /GeneralPractice/973. K Closest Points to Origin.py: -------------------------------------------------------------------------------- 1 | """ 2 | Accepted 3 | 600 ms 4 | Beats 48.88% 5 | """ 6 | import heapq 7 | from typing import List 8 | class Solution: 9 | def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: 10 | 11 | k_points = [] 12 | for point in points: 13 | incoming_dist = point[0] * point[0] + point[1] * point[1] 14 | 15 | if len(k_points) < k: 16 | heapq.heappush(k_points, (-incoming_dist, point[0], point[1])) 17 | else: 18 | temp_pop = heapq.heappop(k_points) 19 | if incoming_dist > -temp_pop[0]: 20 | heapq.heappush(k_points, temp_pop) 21 | else: 22 | heapq.heappush(k_points, (-incoming_dist, point[0], point[1])) 23 | 24 | result = [] 25 | while k_points: 26 | popped = heapq.heappop(k_points) 27 | result.append([popped[1], popped[2]]) 28 | return result 29 | 30 | s=Solution() 31 | print(s.kClosest(points = [[1,3],[-2,2]], k = 1)) 32 | print(s.kClosest(points = [[3,3],[5,-1],[-2,4]], k = 2)) -------------------------------------------------------------------------------- /LeetCodePractice/734. Sentence Similarity.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class Solution(object): 4 | def areSentencesSimilar(self, words1, words2, pairs): 5 | """ 6 | :type words1: List[str] 7 | :type words2: List[str] 8 | :type pairs: List[List[str]] 9 | :rtype: bool 10 | """ 11 | if len(words1) != len(words2): 12 | return False 13 | if len(words1) == len(words2) and len(words1) == 0: 14 | return True 15 | if ([words1[0], words2[0]] in pairs or words1[0] == words2[0] or [words2[0], words1[0]] in pairs): 16 | return self.areSentencesSimilar(words1[1:], words2[1:], pairs) 17 | else: 18 | return False 19 | 20 | s=Solution() 21 | assert s.areSentencesSimilar(["great"], ["great"], []) == True 22 | assert s.areSentencesSimilar(["great", "acting", "skills"], ["fine", "drama", "talent"], [["great", "fine"], ["acting","drama"], ["skills","talent"]]) == True 23 | 24 | assert s.areSentencesSimilar(["great","acting","skills"], ["fine","painting","talent"], [["great","fine"],["drama","acting"],["skills","talent"]]) == False -------------------------------------------------------------------------------- /GeneralPractice/BFS and DFS/797. All Paths From Source to Target.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Runtime: 92 ms, faster than 70.99% of Python online submissions for All Paths From Source to Target. 5 | Memory Usage: 13.9 MB, less than 99.46% of Python online submissions for All Paths From Source to Target. 6 | """ 7 | class Solution(object): 8 | def allPathsSourceTarget(self, graph): 9 | """ 10 | :type graph: List[List[int]] 11 | :rtype: List[List[int]] 12 | """ 13 | 14 | results = [] 15 | path = [] 16 | 17 | self.allPathsSourceTargetUtil(0, path, results, graph) 18 | return results 19 | 20 | 21 | def allPathsSourceTargetUtil(self, startNode, path, results, graph): 22 | if startNode == len(graph) - 1: 23 | results.append(path + [startNode]) 24 | else: 25 | for neighbour in graph[startNode]: 26 | self.allPathsSourceTargetUtil(neighbour, path + [startNode], results, graph) 27 | 28 | s=Solution() 29 | print(s.allPathsSourceTarget([[1,2],[3],[3],[]])) 30 | print(s.allPathsSourceTarget([[4,3,1],[3,2,4],[3],[4],[]])) -------------------------------------------------------------------------------- /HackerRankProblems/Balanced Subsequence.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Sears Dots and Arrow 4 | Balanced Subsequence 5 | 6 | All Test cases passed 7 | """ 8 | 9 | def getBalancedSubSequence(S): 10 | stack = [] 11 | i = 0 12 | while(S[i] == ')'): 13 | i = i + 1 14 | 15 | #Now I have the first place where S[i] = '(' 16 | if ( i == len(S) - 1): 17 | return 0 18 | result = 0 19 | for item in S[i:]: 20 | if (item == '('): 21 | stack.append(item) 22 | elif (item == ')'): 23 | if (len(stack) > 0 and stack.pop(-1) == '('): 24 | result = result + 2 # becuase each () will count for 2 rather than 1 balanced pair 25 | #Else ignore this 26 | return result 27 | 28 | 29 | def inputs(): 30 | SList = [] 31 | T = int(raw_input('')) 32 | for i in range(T): 33 | S = raw_input('') 34 | SList.append(S) 35 | return SList 36 | 37 | if __name__ =="__main__": 38 | SList = inputs() 39 | #['()())', '))))(((', '()(((((()'] 40 | # 41 | 42 | for S in SList: 43 | print getBalancedSubSequence(S) 44 | 45 | 46 | -------------------------------------------------------------------------------- /GeneralPractice/1750. Minimum Length of String After Deleting Similar Ends.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Runtime: 76 ms, faster than 50.00% of Python online submissions for Minimum Length of String After Deleting Similar Ends. 5 | Memory Usage: 14.5 MB, less than 100.00% of Python online submissions for Minimum Length of String After Deleting Similar Ends. 6 | 7 | """ 8 | class Solution(object): 9 | def minimumLength(self, s): 10 | """ 11 | :type s: str 12 | :rtype: int 13 | """ 14 | 15 | left = 0 16 | right = len(s) - 1 17 | 18 | while left < right: 19 | leftChar = s[left] 20 | rightChar = s[right] 21 | 22 | if leftChar != rightChar: 23 | break 24 | 25 | while left < right and s[left] == rightChar: 26 | left += 1 27 | while right >= left and s[right] == leftChar: 28 | right -= 1 29 | 30 | 31 | return right - left + 1 32 | 33 | s=Solution() 34 | assert s.minimumLength("ca") == 2 35 | assert s.minimumLength("cabaabac") ==0 36 | assert s.minimumLength("aabccabba") == 3 -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Expedia1.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | import sys 3 | 4 | # Given an array with pairs such that difference in minimum between a[i] and a[j] such that i < j 5 | def closestNumbers(numbers): 6 | num = [] 7 | for i in range(len(numbers)): 8 | num.append((numbers[i], i)) 9 | num = sorted(num, key=lambda x: x[0]) 10 | print num 11 | 12 | minElement = sys.maxint 13 | for i in range(1, len(numbers)): 14 | if num[i][0] - num[i-1][0] <= minElement: 15 | if num[i][0] - num[i-1][0] < minElement: 16 | result = [] 17 | minElement = num[i][0] - num[i-1][0] 18 | result.append([num[i], num[i-1]]) 19 | 20 | print result 21 | newRes = [] 22 | for _res in result: 23 | partA = _res[0] 24 | partB = _res[1] 25 | 26 | if partA[0] < partB[0]: 27 | newRes.append([partA[0], partB[0]]) 28 | else: 29 | newRes.append([partB[0], partA[0]]) 30 | newRes = sorted(newRes, key=lambda x: x[0]) 31 | for _r in newRes: 32 | print _r[0] ,_r[1] 33 | #print newRes 34 | 35 | 36 | closestNumbers([4, 2, 1, 3]) -------------------------------------------------------------------------------- /GeneralPractice/BFS and DFS/PrintAllPathsInMatrix.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution: 5 | def __init__(self, m, n): 6 | self.m = m 7 | self.n = n 8 | self.grid = [ [ 0 for _ in range(n)] for _ in range(m)] 9 | 10 | def start(self): 11 | 12 | stack=[(0, 0)] 13 | 14 | ways = 0 15 | 16 | while stack: 17 | 18 | popped = stack.pop() 19 | 20 | if popped == (self.m - 1, self.n - 1): 21 | ways += 1 22 | 23 | neigbhours = self.getNeighbours(popped) 24 | 25 | if len(neigbhours) > 0: 26 | stack += neigbhours 27 | 28 | return ways 29 | 30 | def getNeighbours(self, popped): 31 | 32 | right = (popped[0], popped[1] + 1) if popped[1] + 1 < self.n else None 33 | down = (popped[0] + 1, popped[1]) if popped[0] + 1 < self.m else None 34 | 35 | result = [] 36 | if right is not None: 37 | result.append(right) 38 | if down is not None: 39 | result.append(down) 40 | 41 | return result 42 | 43 | s=Solution(3, 3) 44 | print(s.start()) 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /GeneralPractice/TopologicalSort_Method1.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | #This method usses Topological sort 4 | # This approach asusmes it is Directed acyclic graph 5 | # as done by https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/TopologicalSort.java 6 | def sortProcess(process): 7 | 8 | result = [] #Act like stack 9 | visited = set() 10 | 11 | for vertice in process.keys(): 12 | if vertice in visited: 13 | continue 14 | else: 15 | dfs(vertice, process, result, visited) 16 | return result 17 | 18 | def dfs(startPoint, processes, result, visited): 19 | print "Vistied:", startPoint 20 | visited.add(startPoint) 21 | 22 | for neighbour in processes[startPoint]: 23 | if neighbour in visited: 24 | continue 25 | else: 26 | dfs(neighbour, processes, result, visited) 27 | result.append(startPoint) 28 | 29 | 30 | print sortProcess( 31 | { 32 | 'c' : [], 33 | 'a' : [ 'b'] , 34 | 'g' : ['f'], 35 | 'd' : ['c'], 36 | 'e' : 'b', 37 | 'f' : ['d', 'e'], 38 | 'b' : ['c'], 39 | } 40 | ) 41 | 42 | #['a', 'b', 'c', 'e', 'd', 'f', 'g'] -------------------------------------------------------------------------------- /LeetCodePractice/Two Sum.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | """ 4 | 1. Two Sum 5 | Tried two approaches. One works for only positive integer. other works for both positive and negative 6 | """ 7 | def twoSum2(nums, target): 8 | 9 | hashT = dict(); 10 | for i in range(len(nums)): 11 | item = nums[i] 12 | if (hashT.get(target - item, -1) != -1): 13 | return hashT.get(target - item), i 14 | else: 15 | hashT[item] = i 16 | #print hashT 17 | 18 | #The solution below will only work for positive integer. If it is a mix of both positive and negative this will fail 19 | def twoSum(nums, target): 20 | 21 | hash = [-1 for i in range(max(max(nums), target)+1)]; 22 | for i in range(len(nums)): 23 | item = nums[i] 24 | if (target - item >= 0): 25 | if (hash[target - item] != -1): # Element already seen 26 | return hash[target - item], i 27 | else: 28 | hash[item] = i 29 | 30 | if __name__=="__main__": 31 | nums = raw_input('') 32 | nums = nums.replace(',', ' ').split(); 33 | nums = [int(x) for x in nums] 34 | target = int(raw_input('')) 35 | print twoSum2(nums, target) 36 | 37 | -------------------------------------------------------------------------------- /CompaniesHiringQuestions/1658. Minimum Operations to Reduce X to Zero.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Intuition is when you remove elements from left or right. Basically you are left iwth a subarray. 5 | with sum = sum(nums) - x 6 | """ 7 | 8 | class Solution(object): 9 | def minOperations(self, nums, x): 10 | """ 11 | :type nums: List[int] 12 | :type x: int 13 | :rtype: int 14 | """ 15 | 16 | target = sum(nums) - x 17 | 18 | if target < 0: 19 | return -1 20 | if target == 0: 21 | return len(nums) 22 | 23 | cur_sum = 0 24 | numOfElements = -1 25 | left = 0 26 | for i in range(len(nums)): 27 | cur_sum += nums[i] 28 | 29 | while cur_sum >= target: 30 | if cur_sum == target: 31 | numOfElements = max(numOfElements, i - left + 1) 32 | cur_sum -= nums[left] 33 | left += 1 34 | return len(nums) - numOfElements if numOfElements != -1 else -1 35 | 36 | s=Solution() 37 | assert s.minOperations(nums = [1,1,4,2,3], x = 5) == 2 38 | assert s.minOperations(nums = [5,6,7,8,9], x = 4) == -1 39 | -------------------------------------------------------------------------------- /LeetCodePractice/270. Closest Binary Search Tree Value.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | 66 / 66 test cases passed. 4 | Status: Accepted 5 | Runtime: 53 ms 6 | 7 | Beats: 72% 8 | """ 9 | import sys 10 | class TreeNode(object): 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | class Solution(object): 17 | result = sys.maxint 18 | result_val = 0 19 | def closestValue(self, root, target): 20 | """ 21 | :type root: TreeNode 22 | :type target: float 23 | :rtype: int 24 | """ 25 | if root is None: 26 | return None 27 | 28 | def findMin(root, target): 29 | if abs(root.val - target) < self.result: 30 | self.result = abs(root.val - target) 31 | self.result_val = root.val 32 | 33 | if self.result == 0: 34 | self.result_val = root.val 35 | return self.result_val 36 | 37 | if target < root.val: 38 | return self.closestValue(root.left, target) 39 | else: 40 | return self.closestValue(root.right, target) 41 | findMin(root, target) 42 | return self.result_val 43 | -------------------------------------------------------------------------------- /LeetCodePractice/Missing Number.py: -------------------------------------------------------------------------------- 1 | """ 2 | 268. Missing Number 3 | Used Binary search. Rather than this I could have used xor thing becuase numbers are not necessarily sorted. 4 | 121 / 121 test cases passed. 5 | Status: Accepted 6 | Runtime: 65 ms 7 | """ 8 | class Solution(object): 9 | def missingNumberUtil(self, nums, left, right): 10 | if (left > right): 11 | return left 12 | mid = (right + left)/2 13 | if ( (mid == 0 and nums[mid] == 1) or (nums[mid] - mid == 1 and nums[mid-1] == mid-1)): 14 | return mid 15 | if (nums[mid] == mid): #Go right 16 | return self.missingNumberUtil(nums, mid + 1, right) 17 | else: 18 | return self.missingNumberUtil(nums, left, mid - 1) 19 | 20 | def missingNumber(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: int 24 | """ 25 | nums=sorted(nums) 26 | if (len(nums) == 1): 27 | if (nums[0] == 0): 28 | return 1 29 | if (nums[0] == 1): 30 | return 0; 31 | return self.missingNumberUtil(nums, 0, len(nums) - 1) 32 | 33 | s=Solution() 34 | print s.missingNumber([0, 1, 3]) -------------------------------------------------------------------------------- /GeneralPractice/739. Daily Temperatures.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def dailyTemperatures(self, T): 6 | """ 7 | :type T: List[int] 8 | :rtype: List[int] 9 | """ 10 | 11 | result = [0 for i in range(len(T))] 12 | stack = [] #stack of indices 13 | 14 | i = 0 15 | while i < len(T): 16 | if len(stack) == 0: 17 | stack.append(i) 18 | i = i + 1 19 | else: 20 | incoming = T[i] 21 | topIndex = stack.pop() 22 | 23 | while topIndex != -1 and incoming > T[topIndex]: 24 | result[topIndex] = i - topIndex 25 | if (len(stack) > 0): 26 | topIndex = stack.pop() 27 | else: 28 | topIndex = -1 29 | if incoming <= T[topIndex]: 30 | stack.append(topIndex) 31 | 32 | stack.append(i) 33 | i = i + 1 34 | 35 | 36 | return result 37 | 38 | s=Solution() 39 | print(s.dailyTemperatures([73, 74, 75, 71, 69, 72, 76, 73])) 40 | print(s.dailyTemperatures([1,3,4,2])) -------------------------------------------------------------------------------- /GeneralPractice/282. Expression Add Operators.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def addOperators(self, num: str, target: int) -> List[str]: 6 | 7 | all_results = [] 8 | self.dfs(num, 0, target, "", all_results) 9 | return all_results 10 | 11 | def dfs(self, nums, i, target, path_so_far, all_results): 12 | if i >= len(nums): 13 | return 14 | path_so_far += str(nums[i]) 15 | 16 | if i == len(nums) - 1: 17 | print(path_so_far) 18 | 19 | if not path_so_far.startswith('0') and \ 20 | not path_so_far.find('/0') >= 0 and \ 21 | eval(path_so_far) == target: 22 | all_results.append(path_so_far) 23 | else: 24 | for operator in ['+', '-', '*', '/']: 25 | self.dfs(nums, i + 1, target, path_so_far + operator, all_results) 26 | self.dfs(nums, i + 1, target, path_so_far, all_results) 27 | 28 | # Example usage 29 | 30 | 31 | s = Solution() 32 | #print(s.addOperators("123", 6)) 33 | #print(s.addOperators("232", 8)) 34 | #print(s.addOperators("3456237490", 9191)) 35 | print(s.addOperators("125", 7)) 36 | print("done") 37 | -------------------------------------------------------------------------------- /LeetCodePractice/544. Output Contest Matches.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | """ 3 | 12 / 12 test cases passed. 4 | Status: Accepted 5 | Runtime: 52 ms 6 | """ 7 | class Solution(object): 8 | def findContestMatch(self, n): 9 | """ 10 | :type n: int 11 | :rtype: str 12 | """ 13 | if n == 1: 14 | return (1) 15 | list1, list2 = list(), list() 16 | for i in range(n): 17 | list1.append(i + 1) 18 | 19 | while True: 20 | while list1: 21 | poppedA = list1.pop(0) 22 | poppedB = list1.pop() 23 | list2.append((poppedA, poppedB)) 24 | 25 | if len(list1) == 0 and len(list2) == 1: 26 | return str(list2[0]).replace(" ", "") 27 | 28 | while list2: 29 | poppedA = list2.pop(0) 30 | poppedB = list2.pop() 31 | list1.append((poppedA, poppedB)) 32 | 33 | if len(list2) == 0 and len(list1) == 1: 34 | return str(list1[0]).replace(" ", "") 35 | 36 | s=Solution() 37 | print s.findContestMatch(2) 38 | print s.findContestMatch(4) 39 | print s.findContestMatch(8) 40 | print s.findContestMatch(16) -------------------------------------------------------------------------------- /LeetCodePractice/720. Longest Word in Dictionary.py: -------------------------------------------------------------------------------- 1 | 2 | __author__ = 'deepika' 3 | 4 | 5 | class Solution(object): 6 | def longestWord(self, words): 7 | """ 8 | :type words: List[str] 9 | :rtype: str 10 | """ 11 | result = [] 12 | for _word in sorted(words, key=lambda x: len(x), reverse=True): 13 | if len(result) > 0 and len(_word) < len(result[0]): 14 | continue 15 | if self.check(_word, words): 16 | result.append(_word) 17 | 18 | if len(result) > 1: 19 | return sorted(result)[0] 20 | return result[0] 21 | 22 | 23 | def check(self, word, words): 24 | if len(word) == 0 and word in words: 25 | return True 26 | elif len(word) == 0 and word not in words: 27 | return False 28 | if len(word) == 1 and word in words: 29 | return True 30 | elif len(word) == 1 and word not in words: 31 | return False 32 | return word[:-1] in words and self.check(word[:-1], words) 33 | 34 | s=Solution() 35 | 36 | print s.longestWord(["w","wo","wor","worl", "world"]) 37 | print s.longestWord(["a", "banana", "app", "appl", "ap", "apply", "apple"]) -------------------------------------------------------------------------------- /LeetCodePractice/155. Min Stack.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 18 / 18 test cases passed. 5 | Status: Accepted 6 | Runtime: 85 ms 7 | """ 8 | class MinStack(object): 9 | 10 | def __init__(self): 11 | """ 12 | initialize your data structure here. 13 | """ 14 | self.stack = [] 15 | self.minStack = [] 16 | 17 | def push(self, x): 18 | """ 19 | :type x: int 20 | :rtype: void 21 | """ 22 | self.stack.append(x) 23 | if len(self.minStack) == 0: 24 | self.minStack.append(x) 25 | else: 26 | element = self.minStack[-1] 27 | if element > x: 28 | self.minStack.append(x) 29 | else: 30 | self.minStack.append(element) 31 | 32 | 33 | def pop(self): 34 | """ 35 | :rtype: void 36 | """ 37 | if self.minStack: 38 | self.minStack.pop() 39 | return self.stack.pop() 40 | 41 | def top(self): 42 | """ 43 | :rtype: int 44 | """ 45 | return self.stack[-1] 46 | 47 | def getMin(self): 48 | """ 49 | :rtype: int 50 | """ 51 | return self.minStack[-1] 52 | 53 | -------------------------------------------------------------------------------- /LeetCodePractice/680. Valid Palindrome II.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 460 / 460 test cases passed. 5 | Status: Accepted 6 | Runtime: 292 ms 7 | 8 | Better than 24.49% 9 | """ 10 | class Solution(object): 11 | def validPalindrome(self, s): 12 | """ 13 | :type s: str 14 | :rtype: bool 15 | """ 16 | if len(s) == 0: 17 | return False 18 | 19 | if len(s) == 1: 20 | return False 21 | 22 | left = 0 23 | right = len(s) - 1 24 | deleteChar = False 25 | while left < right: 26 | if s[left] == s[right]: 27 | left = left + 1 28 | right = right - 1 29 | continue 30 | else: 31 | return self.isPalin(s, left + 1, right) or self.isPalin(s, left, right - 1) 32 | return True 33 | 34 | 35 | def isPalin(self, s, left, right): 36 | while left < right: 37 | if s[left] == s[right]: 38 | left = left + 1 39 | right = right - 1 40 | continue 41 | else: 42 | return False 43 | return True 44 | 45 | 46 | s = Solution() 47 | print s.validPalindrome("aba") 48 | print s.validPalindrome("abca") 49 | 50 | -------------------------------------------------------------------------------- /LeetCodePractice/First Bad Version.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | 4 | 21 / 21 test cases passed. 5 | Status: Accepted 6 | Runtime: 35 ms 7 | 8 | """ 9 | # The isBadVersion API is already defined for you. 10 | # @param version, an integer 11 | # @return a bool 12 | def isBadVersion(version): 13 | if (version >= 1): 14 | return True 15 | return False 16 | 17 | class Solution(object): 18 | def firstBadVersionUtil(self, start, end): 19 | if (start > end): 20 | return 21 | mid = (end + start)/2 22 | if (isBadVersion(mid)): 23 | if (mid == 1): 24 | return mid 25 | if (mid - 1 > 0 and not isBadVersion(mid - 1)): 26 | return mid 27 | else: 28 | return self.firstBadVersionUtil(start, mid - 1) 29 | else: 30 | return self.firstBadVersionUtil(mid + 1, end) 31 | 32 | def firstBadVersion(self, n): 33 | """ 34 | :type n: int 35 | :rtype: int 36 | """ 37 | if (n == 0): 38 | return 0 39 | if (n == 1): 40 | return 1 41 | 42 | return self.firstBadVersionUtil(1, n) 43 | s=Solution() 44 | #print s.firstBadVersion(10) 45 | print s.firstBadVersion(2) -------------------------------------------------------------------------------- /GeneralPractice/752. Open the Lock.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def openLock(self, deadends, target): 6 | """ 7 | :type deadends: List[str] 8 | :type target: str 9 | :rtype: int 10 | """ 11 | dead = set(deadends) 12 | if "0000" in dead: 13 | return -1 14 | q = [("0000", 0)] 15 | dead.add("0000") 16 | while len(q) > 0: 17 | key, dis = q.pop(0) 18 | print(key) 19 | if key == target: 20 | return dis 21 | 22 | neigh = self.getNeigh(key, dead, dis+1) 23 | if len(neigh) > 0: 24 | q.extend(neigh) 25 | return -1 26 | 27 | 28 | def getNeigh(self, state, dead, dis): 29 | output = [] 30 | for i in range(4): 31 | num = int(state[i]) 32 | for a in ((num-1), (num+1)): 33 | tmp = state[:i] + str(a%10) + state[i+1:] 34 | if tmp not in dead: 35 | output.append((tmp, dis)) 36 | dead.add(tmp) 37 | 38 | 39 | return output 40 | 41 | s=Solution() 42 | print(s.openLock(["0201","0101","0102","1212","2002"], "0202") ) 43 | 44 | -------------------------------------------------------------------------------- /GeneralPractice/1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import sys 4 | 5 | class Solution(object): 6 | def maxArea(self, h, w, horizontalCuts, verticalCuts): 7 | """ 8 | :type h: int 9 | :type w: int 10 | :type horizontalCuts: List[int] 11 | :type verticalCuts: List[int] 12 | :rtype: int 13 | """ 14 | 15 | horizontalCuts = sorted(horizontalCuts) 16 | verticalCuts = sorted(verticalCuts) 17 | 18 | horizontal_max = self.max_difference(horizontalCuts, h) 19 | vertical_max = self.max_difference(verticalCuts, w) 20 | 21 | return horizontal_max * vertical_max 22 | 23 | 24 | def max_difference(self, array, dimension): 25 | max_diff = max(array[0], dimension - array[len(array) - 1]) 26 | 27 | for i in range(0, len(array) - 1): 28 | max_diff = max(max_diff, array[i+1] - array[i]) 29 | 30 | return max_diff 31 | 32 | s=Solution() 33 | print(s.maxArea(h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3])) 34 | print(s.maxArea(h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1])) 35 | print(s.maxArea(h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3])) -------------------------------------------------------------------------------- /Internships/NextCapital/ArrayProcessor.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 1. If i is a multiple of 2 and i is greater than 0, 4 | # array[i] = array[i] + array[i - 1] 5 | # 2. If i is a multiple of 3 and i is greater than 0 and i + 1 < L, 6 | # Swap array[i] and array[i + 1] 7 | # 3. If i is a multiple of 5 and i is greater than 0, 8 | # array[i] = array[i] * 2 9 | # 4. If i is a multiple of 7 or when no other rules apply, 10 | # array[i] = array[i] - 1 11 | # 12 | # __author__ = 'deepika' 13 | 14 | 15 | def processArray(array): 16 | result = [0 for i in range(len(array))] 17 | 18 | for i in range(len(array)): 19 | applied=False 20 | if (i%2==0 and i > 0): 21 | array[i] = array[i] + array[i-1] 22 | applied=True 23 | if (i%3==0 and i > 0 and i+1 < len(array)): 24 | array[i+1], array[i] = array[i], array[i+1] 25 | applied=True 26 | if (i%5==0 and i > 0): 27 | array[i] = array[i]*2 28 | applied=True 29 | if(i%7==0 or not applied): 30 | array[i] = array[i] - 1 31 | return array 32 | if __name__=="__main__": 33 | array = [1,2 ,3 ,4 , 5,6] 34 | print processArray(array) 35 | array = [0, 1,2 ,3 ,4 ] 36 | print processArray(array) -------------------------------------------------------------------------------- /HackerRankProblems/Jim and the Skyscrapers.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | 5 | 6 | n = int(raw_input()) 7 | 8 | arr = raw_input() 9 | arr = arr.split() 10 | 11 | matrix = [ [0 for _ in range(n)] for i in range(n)] 12 | 13 | result = list() 14 | 15 | #for i in range(n): 16 | # matrix[i][i] = 1 17 | 18 | for length in range(2, n+1): 19 | for i in range(n): 20 | #print " i = ", i, " j = ", len + i - 1 21 | j = length + i - 1 22 | if (j >= n): 23 | continue 24 | if (length == 2): 25 | if ( arr[i] == arr[j]): 26 | matrix[i][j] = 1 27 | result.append((i+1, j+1)) 28 | elif(length == 3): 29 | if (arr[i] == arr[j] and arr[i] > arr[i+1]): 30 | matrix[i][j] = 1 31 | result.append((i+1, j+1)) 32 | else: 33 | if (length % 2 != 0): #Odd 34 | if (matrix[i+1][j-1] == 1 and arr[i+1] < arr[i]): 35 | matrix[i][j] = 1 36 | result.append((i+1, j+1)) 37 | else: 38 | if (matrix[i][j-1] == 1 and arr[j-1] == arr[j]): 39 | matrix[i][j] = 1 40 | result.append((i+1, j+1)) 41 | print str(len(result) * 2) -------------------------------------------------------------------------------- /LeetCodePractice/513. Find Bottom Left Tree Value.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 74 / 74 test cases passed. 5 | Status: Accepted 6 | Runtime: 102 ms 7 | """ 8 | class TreeNode(object): 9 | def __init__(self, x): 10 | self.val = x 11 | self.left = None 12 | self.right = None 13 | 14 | class Solution(object): 15 | result = None 16 | maxDepth = -1 17 | def findBottomLeftValue(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: int 21 | """ 22 | depth = 0 23 | self.finBottomUtil(root, depth) 24 | return self.result 25 | 26 | def finBottomUtil(self, root, depth): 27 | 28 | if root is None: 29 | return None 30 | 31 | if depth > self.maxDepth: 32 | self.maxDepth = depth 33 | #print "Updating result to :", root.val, " depth: ", self.maxDepth 34 | self.result = root.val 35 | 36 | self.finBottomUtil(root.left, depth + 1) 37 | self.finBottomUtil(root.right, depth + 1) 38 | 39 | 40 | root2=TreeNode(1) 41 | root2.left=TreeNode(2) 42 | root2.right=TreeNode(5) 43 | root2.left.left=TreeNode(3) 44 | root2.left.right=TreeNode(4) 45 | s=Solution() 46 | print s.findBottomLeftValue(root2) -------------------------------------------------------------------------------- /GeneralPractice/1631. Path With Minimum Effort.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import sys 4 | class Solution(object): 5 | def minimumEffortPath(self, heights): 6 | """ 7 | :type heights: List[List[int]] 8 | :rtype: int 9 | """ 10 | 11 | m = len(heights) 12 | n = len(heights[0]) 13 | efforts = [ [sys.maxint for i in range(n)] for j in range(m)] 14 | 15 | efforts[0][0] = heights[0][0] 16 | 17 | for i in range(m): 18 | for j in range(n): 19 | if i == 0 and j == 0: 20 | continue 21 | efforts[i][j] = min(efforts[i][j], abs( heights[i][j] - max (heights[i-1][j] if i-1>=0 else -sys.maxint, 22 | heights[i][j-1] if j-1 >= 0 else -sys.maxint, 23 | heights[i+1][j] if i+1 < m else -sys.maxint, 24 | heights[i][j+1] if j+1 < n else -sys.maxint) ) ) 25 | 26 | print(efforts) 27 | return efforts[m-1][n-1] 28 | 29 | s=Solution() 30 | print(s.minimumEffortPath([[1,2,2],[3,8,2],[5,3,5]])) 31 | print(s.minimumEffortPath([[1,2,3],[3,8,4],[5,3,5]])) 32 | print(s.minimumEffortPath([[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]])) -------------------------------------------------------------------------------- /GeneralPractice/1578. Minimum Deletion Cost to Avoid Repeating Letters.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | """ 5 | Incomplete but I got the Algo 6 | """ 7 | import sys 8 | class Solution(object): 9 | def minCost(self, s, cost): 10 | """ 11 | :type s: str 12 | :type cost: List[int] 13 | :rtype: int 14 | """ 15 | 16 | if len(s) in [0, 1]: 17 | return 0 18 | 19 | overall_result = 0 20 | window_max_cost = -1 21 | window_sum = 0 22 | i = 0 23 | for i in range(0, len(s)): 24 | if i > 0 and s[i] == s[i-1]: 25 | window_sum += cost[i] 26 | window_max_cost = max(cost[i], window_max_cost) 27 | else: 28 | overall_result += 0 if window_sum == -1 else window_sum - window_max_cost 29 | window_max_cost = -1 # rest the value 30 | window_sum = 0 31 | overall_result += 0 if window_sum == -1 else window_sum - window_max_cost 32 | print(overall_result) 33 | return overall_result 34 | 35 | s=Solution() 36 | assert s.minCost(s = "abaac", cost = [1,2,3,4,5]) == 3 37 | assert s.minCost(s = "abc", cost = [1,2,3]) == 0 38 | assert s.minCost(s = "aabaa", cost = [1,2,3,4,1]) == 2 39 | -------------------------------------------------------------------------------- /GeneralPractice/Sum of k smallest elements in BST.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | class TreeNode(object): 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | class Solution(object): 9 | 10 | def findkSmallestSum(self, root, k): 11 | count = 0 12 | totalSum = 0; 13 | self._findkSmallestSumUtil(root, k, count, totalSum) 14 | return totalSum 15 | 16 | def _findkSmallestSumUtil(self, root, k, count, totalSum): 17 | if root is None: 18 | return 0 19 | 20 | if (count > k): 21 | return 0 22 | 23 | totalSum += self._findkSmallestSumUtil(root.left, k, count, totalSum) 24 | 25 | if count >=k: 26 | return totalSum 27 | 28 | totalSum += root.val 29 | count += 1; # Is getting reset in every call. 30 | 31 | totalSum += self._findkSmallestSumUtil(root.right, k, count, totalSum) 32 | return totalSum 33 | 34 | 35 | 36 | s=Solution() 37 | t=TreeNode(10) 38 | t.left=TreeNode(5) 39 | t.right=TreeNode(15) 40 | t.left.left=TreeNode(2) 41 | t.left.right=TreeNode(7) 42 | t.right.left=TreeNode(12) 43 | t.right.right=TreeNode(20) 44 | t.left.right.left=TreeNode(6) 45 | 46 | 47 | print(s.findkSmallestSum(t, 3)) -------------------------------------------------------------------------------- /HackerRankProblems/Emails, emails everywhere!.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import queue as Q 4 | 5 | class Skill(object): 6 | def __init__(self, priority, timestamp, description): 7 | self.priority = priority 8 | self.timestamp = timestamp 9 | self.name = description 10 | 11 | def __cmp__(self, other): 12 | if (self.priority > other.priority): 13 | return -1 14 | elif(self.priority < other.priority): 15 | return 1 16 | else: #If equal 17 | if (self.timestamp < other.timestamp): 18 | return -1 19 | elif (self.timestamp > other.timestamp): 20 | return 1 21 | return 0 22 | 23 | def __repr__(self): 24 | #return "[" + str(self.priority) + " " + str(self.timestamp) + " " + str(self.name) + "]" 25 | return self.name 26 | 27 | if __name__ == "__main__": 28 | n = int(raw_input('')) 29 | q = Q.PriorityQueue() 30 | timestamp=0 31 | for _ in range(n): 32 | inputLine = raw_input('') 33 | inputLine = inputLine.split() 34 | if (inputLine[0] == 'store'): 35 | timestamp=timestamp + 1 36 | q.put(Skill(int(inputLine[2]), timestamp, inputLine[1])) 37 | else: 38 | print q.get() 39 | -------------------------------------------------------------------------------- /LeetCodePractice/Find All Anagrams in a String.py: -------------------------------------------------------------------------------- 1 | """ 2 | cannot handle large inputs 3 | """ 4 | import copy 5 | class Solution(object): 6 | def checkIfAnagram(self, s, pCounter, pSize): 7 | for item in s: 8 | item = ord(item) - ord('a') 9 | if(pCounter[item] > 0): 10 | pCounter[item] = pCounter[item] - 1 11 | pSize = pSize - 1 12 | else: 13 | return False 14 | return pSize == 0 15 | def findAnagrams(self, s, p): 16 | """ 17 | :type s: str 18 | :type p: str 19 | :rtype: List[int] 20 | """ 21 | pCounter=[0 for _ in range(27)] 22 | for i in p: 23 | pCounter[ord(i)-ord('a')] = pCounter[ord(i)-ord('a')] + 1 24 | result = [] 25 | i=0 26 | while ( i < len(s)): 27 | #print " Start for i = ", i 28 | if ( pCounter[ ord(s[i]) - ord('a')] > 0): #Found one of the occurence 29 | if (self.checkIfAnagram(s[i:i+len(p)], copy.copy(pCounter), len(p))): 30 | result.append(i) 31 | i = i + 1 32 | 33 | return result 34 | 35 | 36 | s=Solution() 37 | print s.findAnagrams("baa", "aa") 38 | print s.findAnagrams("cbaebabacd", "abc") 39 | print s.findAnagrams("abab", "ab") -------------------------------------------------------------------------------- /LeetCodePractice/Remove K Digits.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | """ 4 | 402. Remove K Digits 5 | 6 | Also 7 | Zappos Coding challenge 8 | given a number in string format say something ike 1234089389 and number n = number of elements u can delete 9 | find the smallest possible number you can make out of these. 10 | """ 11 | def attempt2(s, n): 12 | N = len(s) 13 | targetLen = N - n 14 | result = '' 15 | while(targetLen != 0): 16 | print " choose minimum in : ", s[0:n+1] 17 | min_so_far = min(s[0:n+1]) 18 | result = result + min_so_far 19 | print "=========> result so far: ", result 20 | s = s[s.index(min_so_far) + 1 :] 21 | print "New s = ", s 22 | targetLen = targetLen - 1 23 | print "len(s) - targetLen", len(s), targetLen, " result: ", len(s) - targetLen 24 | n = len(s) - targetLen # because some digits will get auto deleted 25 | 26 | i = 0 27 | while(i < len(result) and ord(result[i]) == ord('0')): 28 | i = i + 1 29 | if (len(result[i:]) == 0): 30 | return "0" 31 | else: 32 | return result[i:] 33 | 34 | if __name__=="__main__": 35 | s = "111117891"; 36 | n = 3 37 | if (n >= len(s)): 38 | print "0" 39 | elif (n == 0): 40 | print s 41 | else: 42 | print attempt2(s, n) -------------------------------------------------------------------------------- /GeneralPractice/1606. Find Servers That Handled Most Number of Requests.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | """ 5 | It is one of those problems in which data structue definition is more challenging than the actual code. 6 | Time complexity : O(n log k) 7 | """ 8 | import heapq 9 | 10 | class Solution(object): 11 | def busiestServers(self, k, arrival, load): 12 | """ 13 | :type k: int 14 | :type arrival: List[int] 15 | :type load: List[int] 16 | :rtype: List[int] 17 | """ 18 | 19 | avail = list(range(k)) 20 | count = [0]*k 21 | 22 | pq = [] 23 | for i, a in enumerate(arrival): 24 | while pq and pq[0][0] <= a: 25 | _, x = heapq.heappop(pq) 26 | heapq.heappush(avail, i + (x-i)%k) 27 | if avail: 28 | poppedServer = heapq.heappop(avail) % k 29 | heapq.heappush(pq, (a + load[i], poppedServer)) 30 | count[poppedServer] += 1 31 | max_count = max(count) 32 | return [i for i in range(k) if count[i] == max_count] # this is important. Finding max again and again will increase the time complexity of this problem. 33 | 34 | 35 | s=Solution() 36 | print(s.busiestServers(k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] )) 37 | 38 | -------------------------------------------------------------------------------- /LeetCodePractice/563. Binary Tree Tilt.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | class TreeNode(object): 4 | def __init__(self, x): 5 | self.val = x 6 | self.left = None 7 | self.right = None 8 | 9 | class Solution(object): 10 | def findTilt(self, root): 11 | """ 12 | :type root: TreeNode 13 | :rtype: int 14 | """ 15 | tilt=0 16 | ls=0 17 | rs=0 18 | print self.findTiltUtil(root, tilt,ls,rs) 19 | print "result:", ls, rs 20 | 21 | def findTiltUtil(self, root, tilt,ls,rs): 22 | if (root is None): 23 | return 0 24 | lst = self.findTiltUtil(root.left, tilt, ls, rs) 25 | rst = self.findTiltUtil(root.right, tilt, ls, rs) 26 | ls = ls + lst 27 | rs = rs + rst 28 | print "at root.data : ", root.val, ls, rs 29 | 30 | if (root.left is None and root.right is None): 31 | return root.val 32 | return root.val + ls + rs 33 | 34 | root=TreeNode(1) 35 | root.left=TreeNode(2) 36 | root.right=TreeNode(3) 37 | root.left.left=TreeNode(4) 38 | root.left.right=TreeNode(5) 39 | 40 | s=Solution() 41 | s.findTilt(root) 42 | 43 | root=TreeNode(1) 44 | root.left=TreeNode(2) 45 | root.right=TreeNode(3) 46 | root.left.right=TreeNode(4) 47 | #s.findTilt(root) 48 | -------------------------------------------------------------------------------- /GeneralPractice/3 Minimas.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | def check_for(array, i, j): 4 | element = array[i][j] 5 | n = len(array) 6 | m = len(array[0]) 7 | 8 | for k in range(-1, 2, 1): 9 | for l in range(-1, 2, 1): 10 | if k == 0 and l == 0: 11 | continue 12 | i_prime = i + k 13 | j_prime = j + l 14 | if (i_prime >= n or i_prime < 0 or j_prime >= m or j_prime < 0): 15 | continue 16 | if array[i_prime][j_prime] <= element: 17 | return False 18 | return True 19 | 20 | def find_minima(size, array): 21 | n = len(array) 22 | m = len(array[0]) 23 | 24 | result = [] 25 | for i in range(n): 26 | for j in range(m): 27 | print "Checking for :", array[i][j] 28 | if check_for(array, i, j): 29 | result.append(array[i][j]) 30 | 31 | if len(result) == 0: 32 | return [] 33 | result = sorted(result) 34 | if len(result) > 3: 35 | result = result[0:3] 36 | for i in result: 37 | print i 38 | 39 | n = 5 40 | m = [ 41 | [5., 5., 5., 5., 5.], 42 | [5., 1., 5., 5., 5.], 43 | [5., 5., 5., 4., 5.], 44 | [5., 5., 4., 2., 3.], 45 | [0., 5., 5., 3., 4.] 46 | ] 47 | 48 | print find_minima(n, m) 49 | -------------------------------------------------------------------------------- /LeetCodePractice/563.Binary Tree Tilt.py: -------------------------------------------------------------------------------- 1 | 2 | class TreeNode(object): 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | class Solution(object): 9 | def findTilt(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: int 13 | """ 14 | tilt=[] 15 | ls=0 16 | rs=0 17 | self.findTiltUtil(root, tilt, ls, rs) 18 | return sum(tilt) 19 | 20 | def findTiltUtil(self, root, tilt, ls, rs): 21 | if (root is None): 22 | return 0 23 | lst = self.findTiltUtil(root.left, tilt, ls, rs) 24 | rst = self.findTiltUtil(root.right, tilt, ls, rs) 25 | ls = ls + lst 26 | rs = rs + rst 27 | #print "at root.data : ", root.val, ls, rs, "old tilt : ", tilt 28 | tilt.append(ls - rs if ls >= rs else -(ls - rs)) 29 | #print "Updated tilt to : ", tilt 30 | return root.val + ls + rs 31 | 32 | root=TreeNode(1) 33 | root.left=TreeNode(2) 34 | root.right=TreeNode(3) 35 | root.left.left=TreeNode(4) 36 | root.left.right=TreeNode(5) 37 | 38 | s=Solution() 39 | print s.findTilt(root) 40 | 41 | root=TreeNode(1) 42 | root.left=TreeNode(2) 43 | root.right=TreeNode(3) 44 | root.left.right=TreeNode(4) 45 | print s.findTilt(root) 46 | -------------------------------------------------------------------------------- /LeetCodePractice/366. Find Leaves of Binary Tree.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | """ 3 | 4 | 68 / 68 test cases passed. 5 | Status: Accepted 6 | Runtime: 69 ms 7 | """ 8 | 9 | class TreeNode(object): 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | class Solution(object): 16 | def findLeaves(self, root): 17 | """ 18 | :type root: TreeNode 19 | :rtype: List[List[int]] 20 | """ 21 | result = [] 22 | self.findLeavesUtil(root, result) 23 | print result 24 | 25 | def findLeavesUtil(self, root, result): 26 | if root is None: 27 | return 0 28 | lvl = 1 + max(self.findLeavesUtil(root.left, result), self.findLeavesUtil(root.right, result)) 29 | print root.val, " ", lvl 30 | if (len(result) < lvl): 31 | result.append([]) 32 | result[lvl - 1].append(root.val) 33 | return lvl 34 | 35 | 36 | 37 | root=TreeNode(3) 38 | root.left=TreeNode(2) 39 | root.right=TreeNode(4) 40 | root.left.left=TreeNode(1) 41 | root.right.right=TreeNode(5) 42 | 43 | root2=TreeNode(3) 44 | root2.left=TreeNode(2) 45 | root2.right=TreeNode(5) 46 | root2.left.left=TreeNode(1) 47 | root2.left.right=TreeNode(0) 48 | 49 | s=Solution() 50 | print s.findLeaves(root2) -------------------------------------------------------------------------------- /LeetCodePractice/Remove Duplicates from Sorted Array II.py: -------------------------------------------------------------------------------- 1 | """ 2 | 80. Remove Duplicates from Sorted Array II 3 | 4 | 164 / 164 test cases passed. 5 | Status: Accepted 6 | Runtime: 59 ms 7 | """ 8 | class Solution(object): 9 | def removeDuplicates(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: int 13 | """ 14 | i=0 15 | count = 0 16 | writer = 0 17 | while(i < len(nums)): 18 | end = i 19 | start = i 20 | #print " Start = ", start, "and end = ", end 21 | while (i + 1 < len(nums) and nums[i] == nums[i+1]): 22 | end = end + 1 23 | i = i + 1 24 | 25 | if ( end - start >= 1): 26 | count = count + 2 27 | nums[writer] = nums[i] 28 | writer = writer + 1 29 | nums[writer] = nums[writer - 1] 30 | writer = writer + 1 31 | i = end + 1 32 | else: 33 | nums[writer] = nums[i] 34 | writer = writer + 1 35 | count = count + 1 36 | i = i + 1 37 | nums = nums[0:writer] 38 | return count 39 | 40 | 41 | 42 | 43 | s=Solution() 44 | print s.removeDuplicates([1,1,1,2,2,3]) 45 | print s.removeDuplicates([1,1,1,2]) -------------------------------------------------------------------------------- /CompaniesHiringQuestions/Stripe2020.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Telephonic Coding round: 4 | 5 | Part 1: 6 | The questions was that say you are given a table with rows and columns . Given a column find the row that contains minimum value 7 | for that column. 8 | 9 | for ex: 10 | Table = [ { a:1, b : 2, c: 3} , { a : 10}] 11 | minBycolumn(Table, "a") -> return { a:1, b : 2, c: 3} 12 | minBycolumn(Table, "b") -> return { a : 10} because if a column is not present in a row assume it is 0. 13 | So, basically {a : 10} can actually be thought as { a : 10, b : 0, c: 0} 14 | 15 | since, if we have two rows as of now so you can assume columns are a, b and c 16 | However, as you go forward the columns can change. 17 | 18 | Solution: Save dataset as List Basically each row will be represented as a new hasmap and then appended to the List. 19 | 20 | 21 | Part 2: 22 | Now, you want to sort by multiple columns. Say for col1 there was a tie then sort by next column and so on. 23 | 24 | Table : [ 25 | { x : 1, y : 2, z : 3}, 26 | { x : 1, y : 2, z : 2}, 27 | {x : 1, y : 2, z : 4 } 28 | ] 29 | 30 | minByColumn(Table, ["x", "y", "z"]) -> return { x : 1, y : 2, z : 2} 31 | 32 | The interviewer was happy with the approach. Allowed to you Google. Run/space time complexity was not a concern. 33 | 34 | Received a reject within 2 hours of the interview 35 | """ -------------------------------------------------------------------------------- /LeetCodePractice/661. Image Smoother.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Accepted 5 | """ 6 | import math 7 | 8 | class Solution(object): 9 | def getAverage(self, M, i, j): 10 | 11 | ValidNeighbours = 0 12 | total_sum = 0 13 | for _i in range(-1, 2): 14 | for _j in range(-1, 2): 15 | i_prime = i + _i 16 | j_prime = j + _j 17 | if (i_prime >= 0 and j_prime >=0 and i_prime< len(M) and j_prime < len(M[0])): 18 | #print "i_prime: ", i_prime, " j_prime: ", j_prime 19 | ValidNeighbours = ValidNeighbours + 1 20 | total_sum = total_sum + M[i_prime][j_prime] 21 | return int(math.floor(total_sum/ValidNeighbours)) 22 | 23 | def imageSmoother(self, M): 24 | """ 25 | :type M: List[List[int]] 26 | :rtype: List[List[int]] 27 | """ 28 | m = len(M) 29 | n = len(M[0]) 30 | M_new = [ [0 for i in range(n)] for j in range(m)] 31 | for i in range(len(M)): 32 | for j in range(len(M[0])): 33 | M_new[i][j] = self.getAverage(M, i, j) 34 | return M_new 35 | 36 | s=Solution() 37 | M=[[1,1,1], [1,0,1], [1,1,1]] 38 | #print s.imageSmoother(M) 39 | 40 | print s.imageSmoother([[2,3,4],[5,6,7],[8,9,10],[11,12,13],[14,15,16]]) 41 | -------------------------------------------------------------------------------- /LeetCodePractice/230. Kth Smallest Element in a BST.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 91 / 91 test cases passed. 5 | Status: Accepted 6 | Runtime: 72 ms 7 | 8 | 91.1% better. I think catch here is breaking when *if self.result is not None:* 9 | """ 10 | class TreeNode(object): 11 | def __init__(self, x): 12 | self.val = x 13 | self.left = None 14 | self.right = None 15 | 16 | class Solution(object): 17 | count = 0 18 | result = None 19 | def kthSmallestUtil(self, root, k): 20 | if root is None: 21 | return 22 | if self.result is not None: 23 | return self.result 24 | 25 | self.kthSmallestUtil(root.left, k) 26 | self.count = self.count + 1 27 | if (self.count == k): 28 | self.result = root.val 29 | return root.val 30 | self.kthSmallestUtil(root.right, k) 31 | 32 | def kthSmallest(self, root, k): 33 | """ 34 | :type root: TreeNode 35 | :type k: int 36 | :rtype: int 37 | """ 38 | self.kthSmallestUtil(root, k) 39 | return self.result 40 | 41 | 42 | 43 | 44 | root1=TreeNode(9) 45 | root1.left=TreeNode(7) 46 | root1.left.left=TreeNode(6) 47 | root1.left.right=TreeNode(8) 48 | root1.right=TreeNode(10) 49 | 50 | s=Solution() 51 | print s.kthSmallest(root1, 3) 52 | 53 | -------------------------------------------------------------------------------- /GeneralPractice/538. Convert BST to Greater Tree.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | # Definition for a binary tree node. 4 | 5 | """ 6 | Runtime: 176 ms, faster than 9.42% of Python online submissions for Convert BST to Greater Tree. 7 | Memory Usage: 17.1 MB, less than 61.59% of Python online submissions for Convert BST to Greater Tree. 8 | """ 9 | class TreeNode(object): 10 | def __init__(self, val=0, left=None, right=None): 11 | self.val = val 12 | self.left = left 13 | self.right = right 14 | 15 | class Solution(object): 16 | postOrderSum = 0 17 | def convertBST(self, root): 18 | """ 19 | :type root: TreeNode 20 | :rtype: TreeNode 21 | """ 22 | 23 | self.convertBSTUtil(root) 24 | return root 25 | 26 | def convertBSTUtil(self, root): 27 | if root is None: 28 | return 0 29 | 30 | 31 | self.convertBSTUtil(root.right) 32 | print("First step ", root.val ) 33 | self.postOrderSum+= root.val 34 | root.val = self.postOrderSum 35 | print(root.val, " ", self.postOrderSum ) 36 | 37 | self.convertBSTUtil(root.left) 38 | 39 | 40 | 41 | 42 | 43 | root=TreeNode(2) 44 | root.left=TreeNode(0) 45 | root.right=TreeNode(3) 46 | root.left.left=TreeNode(-4) 47 | root.left.right=TreeNode(1) 48 | s=Solution() 49 | s.convertBST(root) -------------------------------------------------------------------------------- /CompaniesHiringQuestions/AditiFriend1.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def solution(inputTable): 5 | 6 | #Am, Mex, Seafood 7 | dictionary = {} 8 | specialities = set() 9 | for line in inputTable: 10 | if line[0] not in dictionary: 11 | dictionary[line[0]] = {} 12 | 13 | if line[1] not in dictionary[line[0]]: 14 | dictionary[line[0]][line[1]] = line[2] 15 | specialities.add(line[1]) 16 | else: 17 | dictionary[line[0]][line[1]] += line[2] 18 | 19 | sortedKeys = sorted(dictionary) 20 | specialities = sorted(specialities) 21 | print(sortedKeys) 22 | print(specialities) 23 | 24 | result = [] 25 | for k in sortedKeys: 26 | line = [] 27 | city = dictionary[k] 28 | 29 | for sp in specialities: 30 | if sp in city: 31 | line.append(int(city[sp])) 32 | else: 33 | line.append(0) 34 | result.append(line) 35 | return result 36 | 37 | 38 | string = [ 39 | [ "Boston", "Mexican", "163"], 40 | [ "Boston", "Seafood", "194"], 41 | [ "Boston", "Smoothie", "14"], 42 | [ "Los Angeles", "American", "1239"], 43 | [ "Los Angeles", "Mexican", "1389"], 44 | [ "Los Angeles", "Seafood", "556"], 45 | [ "Los Angeles", "Burger", "5"], 46 | 47 | 48 | ] 49 | print(solution(string)) -------------------------------------------------------------------------------- /LeetCodePractice/62. Unique Paths.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 61 / 61 test cases passed. 5 | Status: Accepted 6 | Runtime: 135 ms 7 | """ 8 | class Solution(object): 9 | def uniquePaths1(self, m, n): 10 | """ 11 | :type m: int 12 | :type n: int 13 | :rtype: int 14 | """ 15 | if m == 1 or n == 1: 16 | return 1 17 | return self.uniquePaths(m-1, n) + self.uniquePaths(m, n-1) 18 | 19 | def uniquePaths(self, m, n): 20 | count = [[0 for x in range(n)] for y in range(m)] 21 | print count 22 | # Count of paths to reach any 23 | # cell in first column is 1 24 | for i in range(m): 25 | count[i][0] = 1; 26 | 27 | # Count of paths to reach any 28 | # cell in first column is 1 29 | for j in range(n): 30 | count[0][j] = 1; 31 | print count 32 | if m == 1 or n == 1: 33 | return count[m-1][n-1] 34 | # Calculate count of paths for other 35 | # cells in bottom-up 36 | # manner using the recursive solution 37 | for i in range(1, m): 38 | for j in range(n): 39 | print "Assigning value to : ", i, j 40 | count[i][j] = count[i-1][j] + count[i][j-1] 41 | return count[m-1][n-1] 42 | 43 | s=Solution() 44 | print s.uniquePaths(2, 1) -------------------------------------------------------------------------------- /LeetCodePractice/283. Move Zeroes.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | """ 3 | Just 22% better. 4 | 5 | 21 / 21 test cases passed. 6 | Status: Accepted 7 | Runtime: 86 ms 8 | """ 9 | class Solution(object): 10 | def moveZeroes(self, nums): 11 | """ 12 | :type nums: List[int] 13 | :rtype: void Do not return anything, modify nums in-place instead. 14 | """ 15 | zeroPtr = 0 16 | while zeroPtr < len(nums) and nums[zeroPtr] != 0: 17 | zeroPtr = zeroPtr + 1 18 | 19 | nonZeroPtr = zeroPtr + 1 20 | while nonZeroPtr < len(nums) and nums[nonZeroPtr] == 0: 21 | nonZeroPtr = nonZeroPtr + 1 22 | 23 | while True: 24 | if nonZeroPtr in [len(nums), len(nums) + 1, len(nums) ]: 25 | break 26 | nums[zeroPtr] = nums[nonZeroPtr] 27 | zeroPtr = zeroPtr + 1 28 | 29 | nonZeroPtr = nonZeroPtr + 1 30 | while nonZeroPtr < len(nums) and nums[nonZeroPtr] == 0: 31 | nonZeroPtr = nonZeroPtr + 1 32 | 33 | 34 | 35 | #zeroPtr = zeroPtr + 1 36 | while zeroPtr < len(nums): 37 | nums[zeroPtr] = 0 38 | zeroPtr = zeroPtr + 1 39 | print nums 40 | 41 | s=Solution() 42 | s.moveZeroes([0, 1, 0, 3, 12]) 43 | s.moveZeroes([1, 2, 3, 0, 4, 0, 5]) 44 | s.moveZeroes([0, 0, 0, 1, 2, 3, 0, 4, 0, 5]) 45 | -------------------------------------------------------------------------------- /GeneralPractice/124. Binary Tree Maximum Path Sum.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | import sys 4 | 5 | class TreeNode(object): 6 | def __init__(self, x): 7 | self.val = x 8 | self.left = None 9 | self.right = None 10 | 11 | class Solution(object): 12 | def maxPathSum(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | 18 | global_max = -sys.maxint 19 | def maxPathSumHelper(root, global_max): 20 | if root is None: 21 | return 0 22 | 23 | leftSum = maxPathSumHelper(root.left, global_max) 24 | rightSum = maxPathSumHelper(root.right, global_max) 25 | 26 | print("Initially global max at node: " + str(root.val) + " is " + str(global_max)) 27 | 28 | leftMax = max(leftSum, 0) 29 | rightMax = max(rightSum, 0) 30 | 31 | sum_so_far = max(root.val, root.val + leftMax + rightMax) 32 | global_max = max(global_max, sum_so_far) 33 | 34 | print("global max at node: " + str(root.val) + " is " + str(global_max)) 35 | 36 | return sum_so_far 37 | 38 | maxPathSumHelper(root, global_max) 39 | return global_max 40 | 41 | 42 | 43 | 44 | 45 | s=Solution() 46 | root1 = TreeNode(1) 47 | root1.left = TreeNode(2) 48 | root1.right = TreeNode(3) 49 | print(s.maxPathSum(root1)) -------------------------------------------------------------------------------- /LeetCodePractice/644. Maximum Average Subarray II.py: -------------------------------------------------------------------------------- 1 | """ 2 | time limit exceeds 3 | """ 4 | import sys 5 | class Solution(object): 6 | """ 7 | Will find max subarray of size k 8 | """ 9 | def findMaxsumOfK(self, nums, k): 10 | """ 11 | :type nums: List[int] 12 | :type k: int 13 | :rtype: float 14 | """ 15 | #print "Finding max subarray of size : ", k 16 | n = len(nums) 17 | sum_so_far = 0 18 | for i in range(k): 19 | sum_so_far = sum_so_far + nums[i] 20 | curr_sum = sum_so_far 21 | for i in range(k, n): 22 | curr_sum = curr_sum + (nums[i] - nums[i-k]) 23 | sum_so_far = max(sum_so_far, curr_sum) 24 | return sum_so_far 25 | 26 | def findMaxAverage(self, nums, k): 27 | """ 28 | :type nums: List[int] 29 | :type k: int 30 | :rtype: float 31 | """ 32 | if (len(nums) == 1): 33 | return nums[0]*1.0 34 | if (len(nums) == k): 35 | return sum(nums)*1.0/k 36 | max_avg = -sys.maxint 37 | for i in range(k, len(nums)): 38 | avg_of_step = self.findMaxsumOfK(nums, i)*1.0/i 39 | max_avg = max(avg_of_step, max_avg) 40 | return max_avg 41 | 42 | s=Solution() 43 | print s.findMaxAverage([4,0,4,3,3], 5) 44 | print s.findMaxAverage([1,12,-5,-6,50,3], 4) 45 | -------------------------------------------------------------------------------- /LeetCodePractice/Longest Palindromic Substring.py: -------------------------------------------------------------------------------- 1 | """ 2 | 5. Longest Palindromic Substring 3 | Using DP, but works for small inputs. Use Manchester's Algo for long inputs 4 | """ 5 | 6 | def longestPalindromeGFG(s): 7 | #print " Received ", s 8 | n = len(s) 9 | table = [ [ 0 for _ in range(n)] for _ in range(n) ] 10 | start = 0; 11 | maxLen = 1 12 | for i in range(n-1): 13 | table[i][i] = True 14 | if s[i] == s[i+1]: 15 | table[i][i+1] = True 16 | start = i 17 | maxLen = 2 18 | 19 | for k in range(3, n): 20 | for i in range(0, n-k+1): 21 | j = i + k - 1 22 | if (table[i+1][j-1] == True and s[i] == s[j]): 23 | table[i][j] = True 24 | if (k > maxLen): 25 | maxLen = k 26 | start = i 27 | #print " Found palin = ", s[start:start + maxLen] 28 | #print " start = ", i, " and maxLen = ", maxLen 29 | return s[start:start + maxLen] 30 | 31 | if __name__ == "__main__": 32 | print " Run 1 : " 33 | s = "abcdefed" 34 | print longestPalindromeGFG(s) 35 | print " Run 2 : " 36 | s = "aaaa" 37 | print longestPalindromeGFG(s) 38 | print " Run 3 : " 39 | s = "abcda" 40 | print longestPalindromeGFG(s) 41 | print " Run 4 : " 42 | s = "aaaabaaa" 43 | print longestPalindromeGFG(s) -------------------------------------------------------------------------------- /GeneralPractice/1626. Best Team With No Conflicts.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | Runtime: 2072 ms, faster than 42.20% of Python online submissions for Best Team With No Conflicts. 5 | Memory Usage: 13.7 MB, less than 5.05% of Python online submissions for Best Team With No Conflicts. 6 | """ 7 | class Solution(object): 8 | def bestTeamScore(self, scores, ages): 9 | """ 10 | :type scores: List[int] 11 | :type ages: List[int] 12 | :rtype: int 13 | """ 14 | 15 | combinedData = [] 16 | for i in range(len((scores))): 17 | combinedData.append( [ages[i], scores[i]] ) 18 | 19 | combinedData = sorted(combinedData, key=lambda x: (x[0], x[1])) 20 | #print(combinedData) 21 | 22 | ans = [ 0 for i in range(len(combinedData))] 23 | 24 | best = 0 25 | for i in range(len(combinedData)): 26 | ans[i] = combinedData[i][1] 27 | for j in range(0, i): 28 | if combinedData[i][1] >= combinedData[j][1]: 29 | ans[i] = max(ans[i], ans[j] + combinedData[i][1]) 30 | best = max(best, ans[i]) 31 | return best 32 | 33 | s=Solution() 34 | assert s.bestTeamScore(scores = [1,3,5,10,15], ages = [1,2,3,4,5]) == 34 35 | assert s.bestTeamScore( scores = [4,5,6,5], ages = [2,1,2,1]) == 16 36 | assert s.bestTeamScore(scores = [1,2,3,5], ages = [8,9,10,1]) == 6 -------------------------------------------------------------------------------- /GeneralPractice/LinkedIn Rever Depth Sum.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | """ 5 | The problem was something like say you have a list 6 | [1, [2, 3], 4, [5, 6, [7]]] 7 | You have to return the sum such that each sum at each level is multiplied by depth in reverse. 8 | For instance 1, 4 is at level 1 but total depth of the arr = 4 so 1+4 will be multiplies by 4. 9 | [2, 3] is at level 2 but it will be multiplies by 3 10 | 11 | 12 | [1, 2, 3, 4] - Are all at same level. 13 | [1, [2], 3] - 1, 3 are at same level. 14 | """ 15 | 16 | 17 | 18 | def mainFunction(arr): 19 | sum_of_levels = {} 20 | saveLevels(arr, 0, sum_of_levels) 21 | print(sum_of_levels) 22 | rev_depth = len(sum_of_levels.keys()) 23 | 24 | result = 0 25 | for k, v in sum_of_levels.items(): 26 | result += v * rev_depth 27 | rev_depth -= 1 28 | 29 | return result 30 | 31 | def saveLevels(arr, d, sum_of_levels): 32 | 33 | 34 | total = 0 35 | for item in arr: 36 | if isinstance(item, list): 37 | saveLevels(item, d + 1, sum_of_levels) 38 | else: 39 | total += item 40 | 41 | sum_of_levels[d] = sum_of_levels.get(d, 0) + total 42 | 43 | print(mainFunction([1, 2, 3, 4])) 44 | print(mainFunction([1, 2, [3, 4]])) 45 | print(mainFunction([1, 2, [3, [4] ] ])) 46 | print(mainFunction([1, 2, [3], [4] ])) 47 | print(mainFunction([1, [2, 3], 4, [5, 6, [7]]])) -------------------------------------------------------------------------------- /LeetCodePractice/Find the Duplicate Number.py: -------------------------------------------------------------------------------- 1 | """ 2 | 287. Find the Duplicate Number 3 | 4 | 53 / 53 test cases passed. 5 | Status: Accepted 6 | Runtime: 79 ms 7 | 8 | You must not modify the array (assume the array is read only). 9 | You must use only constant, O(1) extra space. 10 | Your runtime complexity should be less than O(n2). 11 | There is only one duplicate number in the array, but it could be repeated more than once. 12 | """ 13 | 14 | class Solution(object): 15 | def findDuplicateUtil(self, nums, left, right): 16 | if (left > right): 17 | return 18 | mid = (left + right)/2 19 | 20 | if (mid == 0): 21 | return nums[mid] 22 | if ( (mid-1 >= 0 and nums[mid - 1] == nums[mid]) or (mid + 1 < len(nums) and nums[mid + 1] == nums[mid])): 23 | return nums[mid] 24 | 25 | def findDuplicatetemp(self, nums): 26 | """ 27 | :type nums: List[int] 28 | :rtype: int 29 | """ 30 | nums=sorted(nums) 31 | self.findDuplicateUtil(nums, 0, len(nums) - 1) 32 | 33 | def findDuplicate(self, nums): 34 | checker = 0 35 | for item in nums: 36 | if (checker & 1< 0): 37 | return item 38 | checker = checker | 1< 0): 26 | head = head.next 27 | n = n - 1 28 | while(head is not None): 29 | head=head.next 30 | prev=start 31 | start=start.next 32 | if (prev is None): 33 | save=save.next 34 | else: 35 | prev.next = start.next 36 | #print "prev now points to : ", prev.next.val if prev.next is not None else "Null" 37 | return save 38 | 39 | 40 | 41 | head=ListNode(1) 42 | #head.next=ListNode(2) 43 | #head.next.next=ListNode(3) 44 | #head.next.next.next=ListNode(4) 45 | #head.next.next.next.next=ListNode(5) 46 | #head.next.next.next.next.next=ListNode(6) 47 | 48 | s=Solution() 49 | s.removeNthFromEnd(head, n=1) 50 | -------------------------------------------------------------------------------- /GeneralPractice/BFS and DFS/133. Clone Graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | Accepted. 3 | 39 ms 4 | Beats 67.65% 5 | Traverses the graph just once. 6 | """ 7 | class Node: 8 | def __init__(self, val = 0, neighbors = None): 9 | self.val = val 10 | self.neighbors = neighbors if neighbors is not None else [] 11 | 12 | 13 | from typing import Optional 14 | from collections import defaultdict 15 | 16 | class Solution: 17 | def cloneGraph(self, node: Optional['Node']) -> Optional['Node']: 18 | if not node: 19 | return None 20 | stack = [node] 21 | oldToNew = defaultdict(Node) 22 | seen_nodes = set() # has a specific node been a source 23 | # n1 -> n2, n3 24 | # We will put n1 to seen only when we have seen it as source to certain destinations 25 | while stack: 26 | popped = stack.pop(-1) 27 | if popped not in seen_nodes: 28 | if popped not in oldToNew: 29 | oldToNew[popped] = Node(popped.val) 30 | seen_nodes.add(popped) 31 | 32 | for neighbour in popped.neighbors: 33 | if neighbour not in oldToNew: 34 | oldToNew[neighbour] = Node(neighbour.val) 35 | stack.append(neighbour) 36 | oldToNew[popped].neighbors.append(oldToNew[neighbour]) 37 | return oldToNew[node] 38 | -------------------------------------------------------------------------------- /LeetCodePractice/572. Subtree of Another Tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 176 / 176 test cases passed. 4 | Status: Accepted 5 | Runtime: 422 ms 6 | """ 7 | 8 | __author__ = 'deepika' 9 | class TreeNode(object): 10 | def __init__(self, x): 11 | self.val = x 12 | self.left = None 13 | self.right = None 14 | 15 | class Solution(object): 16 | def isSubtree(self, s, t): 17 | """ 18 | :type s: TreeNode 19 | :type t: TreeNode 20 | :rtype: bool 21 | """ 22 | if (t is None): 23 | return True 24 | 25 | if (s is None): 26 | return False 27 | 28 | if (self.isIdentical(s, t)): 29 | return True 30 | else: 31 | return self.isSubtree(s.left, t) or self.isSubtree(s.right, t) 32 | 33 | def isIdentical(self, s, t): 34 | if (s is None and t is None): 35 | return True 36 | if ((s is None) or (t is None)): 37 | return False 38 | 39 | return s.val == t.val and \ 40 | self.isIdentical(s.left, t.left) and \ 41 | self.isIdentical(s.right, t.right) 42 | 43 | 44 | 45 | 46 | root1=TreeNode(3) 47 | root1.left=TreeNode(4) 48 | root1.right=TreeNode(5) 49 | root1.left.left=TreeNode(1) 50 | root1.left.right=TreeNode(2) 51 | 52 | root2=TreeNode(4) 53 | root2.left=TreeNode(1) 54 | root2.right=TreeNode(2) 55 | 56 | s=Solution() 57 | print s.isSubtree(root1, root2) -------------------------------------------------------------------------------- /LeetCodePractice/671. Second Minimum Node In a Binary Tree.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | import sys 3 | class TreeNode(object): 4 | def __init__(self, x): 5 | self.val = x 6 | self.left = None 7 | self.right = None 8 | 9 | def __repr__(self): 10 | return str(self.val) 11 | 12 | 13 | class Solution(object): 14 | def findSecondMinimumValue(self, root): 15 | """ 16 | :type root: TreeNode 17 | :rtype: int 18 | """ 19 | return self.findSecondMinimumValueUtil(root) 20 | 21 | def findSecondMinimumValueUtil(self, root): 22 | if root is None: 23 | return None 24 | 25 | #left_minimum, right_minimum = sys.maxint, sys.maxint 26 | left_minimum = self.findSecondMinimumValueUtil(root.left) 27 | right_minimum= self.findSecondMinimumValueUtil(root.right) 28 | 29 | if root.left is None and root.right is None: 30 | return root.val 31 | 32 | if root.left and root.right: 33 | return self._second_min(root.val, left_minimum, right_minimum) 34 | 35 | print "left_minimum: ", left_minimum, "right_minimum: ", right_minimum 36 | 37 | def _second_min(self, a, b, c): 38 | pass 39 | 40 | 41 | s=Solution() 42 | root=TreeNode(2) 43 | root.left=TreeNode(2) 44 | root.right=TreeNode(5) 45 | root.right.left=TreeNode(5) 46 | root.right.right=TreeNode(7) 47 | s.findSecondMinimumValue(root) -------------------------------------------------------------------------------- /LeetCodePractice/161. One Edit Distance.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | def isOneEditDistance(self, s, t): 6 | """ 7 | :type s: str 8 | :type t: str 9 | :rtype: bool 10 | """ 11 | if (abs(len(s) - len(t)) not in [0, 1]): 12 | return False 13 | if (len(s) == 1 and len(t) == 0): 14 | return True 15 | if (len(t) == 1 and len(s) == 0): 16 | return True 17 | if (len(s) == 0 and len(t) == 0): 18 | return False 19 | i, j = 0, 0 20 | diff = 0 21 | while(i < len(s) or j < len(t)): 22 | if ( i >= len(s)): 23 | j = j + 1 24 | elif (j >= len(t)): 25 | i = i + 1 26 | elif (s[i] == t[j]): 27 | i = i + 1 28 | j = j + 1 29 | continue 30 | elif (len(s) == len(t)): 31 | i = i + 1 32 | j = j + 1 33 | 34 | elif (len(s) > len(t)): 35 | i = i + 1 36 | else: 37 | j = j + 1 38 | diff = diff + 1 39 | if (diff > 1): 40 | return False 41 | return diff == 1 42 | 43 | s=Solution() 44 | print s.isOneEditDistance("a", "ac") 45 | print s.isOneEditDistance("abcd", "abce") 46 | print s.isOneEditDistance("abc", "bc") 47 | print s.isOneEditDistance("abc", "ac") 48 | -------------------------------------------------------------------------------- /LeetCodePractice/219. Contains Duplicate II.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | class Solution(object): 5 | #not working 6 | def containsNearbyDuplicate(self, nums, k): 7 | """ 8 | :type nums: List[int] 9 | :type k: int 10 | :rtype: bool 11 | """ 12 | dictionary = dict() 13 | for i in range(len(nums)): 14 | if nums[i] in dictionary: 15 | nums[i].append(i) 16 | if any(lambda x: x >= abs(i - k) and x <= i + k, nums ): 17 | #i + k in nums[i] or abs(i - k) in nums[i]: #Here is the error. 18 | #Any value from i + k to i -k should be checked not only binary 19 | return True 20 | else: 21 | dictionary[nums[i]] = [i] 22 | return False 23 | 24 | #Working 25 | def containsNearbyDuplicate(self, nums, k): 26 | """ 27 | :type nums: List[int] 28 | :type k: int 29 | :rtype: bool 30 | """ 31 | tracker=dict() 32 | for i in range(len(nums)): 33 | if (tracker.get(nums[i], -1) == -1): 34 | tracker[nums[i]] = i 35 | else: # Found duplicate 36 | old_i = tracker[nums[i]] 37 | if ( i - old_i <= k): 38 | return True 39 | else:#Repeat but after k elements 40 | tracker[nums[i]]=i 41 | return False -------------------------------------------------------------------------------- /Internships/NextCapital/2D Lake.py: -------------------------------------------------------------------------------- 1 | 2 | def getWater(heights, distances, i, j): 3 | #if (heights[i] < heights[j]): 4 | 5 | 6 | Height = max(heights[i+1:]) if (heights[i] > heights[j]) else heights[i] 7 | Distance = sum(distances[i:j]) 8 | NumberOfPillars = j - i - 1 9 | 10 | crudeSum=Height * (Distance + NumberOfPillars*1) 11 | sumT = 0 12 | for pillar in range(i+1, j): 13 | sumT = sumT + heights[pillar] * 1 14 | return crudeSum - sumT 15 | 16 | def getMaxLakeVolume(heights, distances): 17 | 18 | i = 0 19 | maxVol = -1 20 | while ( i < len(heights) and i + 1 < len(heights)): 21 | start = i 22 | end = start + 1 23 | 24 | while(end < len(heights) and heights[end] < heights[start]): 25 | #if (end + 1 < len(heights)): 26 | end = end + 1 27 | if(end == len(heights)): 28 | end = end - 1 29 | print " Calling for start = ", start, " and end = ", end 30 | vol = getWater(heights, distances, start, end) 31 | #print " for start = ", start, " and end = ", end, " received vol = ", vol 32 | if (vol > maxVol): 33 | maxVol = vol 34 | i = end 35 | return maxVol 36 | 37 | if __name__=="__main__": 38 | heights = [3, 10, 4, 5, 7] 39 | distances = [1, 2, 3, 4] 40 | 41 | heights = [4, 7, 4, 9, 6] 42 | distances = [3, 9, 6, 2] 43 | 44 | print getMaxLakeVolume(heights, distances) #Expected 108 45 | 46 | -------------------------------------------------------------------------------- /Leetcode_Challenge/Oct 1/Longest Palindrome.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | 95 test cases passed. Absolutely correct 4 | """ 5 | 6 | def longestPalindrome(s): 7 | 8 | charcount = dict() 9 | n = 0 10 | for i in s: 11 | if (charcount.get(i, -1) == -1): 12 | charcount[i] = 1 13 | n = 1 14 | else: 15 | charcount[i] = charcount[i] + 1 16 | n = n + 1 17 | print charcount 18 | result = 0 19 | taken = False #Because only one single occrence character can be taken 20 | someExtraCanBeAdded = False 21 | #print "Total number of element = ", n 22 | 23 | if (len(charcount.items()) == 1): 24 | return charcount.items()[0][1] 25 | for (k, v) in charcount.items(): 26 | 27 | if (v % 2 ==0 ): 28 | result = result + v 29 | elif ( v %2 != 0 and v > 1): 30 | result = result + (v - 1) 31 | someExtraCanBeAdded = True # It means some character was ignored to keep it palin added for test case ababababa. 32 | elif ( v%2 != 0 and v == 1 and not taken): 33 | taken = True 34 | result = result + 1 35 | 36 | if ( not taken and someExtraCanBeAdded): #Added for test case ababababa 37 | result = result + 1 38 | return result 39 | 40 | 41 | if __name__ == '__main__': 42 | s = ["ccc"] 43 | s.append("ababababa") 44 | s.append("abccccdd") 45 | for i in s: 46 | print i , " " , longestPalindrome(i) -------------------------------------------------------------------------------- /GeneralPractice/MergeSort.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | def mergeSort(data): 5 | 6 | left = 0 7 | right = (len(data) - 1) /2 8 | return mergeSortUtil(left, right, data) 9 | 10 | def mergeSortUtil(left, right, arr): 11 | if left > right: 12 | return 13 | if left == right: 14 | return arr 15 | 16 | mid = right - (right - left)/2 17 | 18 | leftArr = mergeSortUtil(left, mid, arr) 19 | rightArr = mergeSortUtil(mid + 1, right, arr) 20 | 21 | return merge(leftArr, rightArr) 22 | 23 | def merge(leftArr, rightArr): 24 | 25 | i, j = 0, 0 26 | result = [0] * (len(leftArr) + len(rightArr)) 27 | k = 0 28 | 29 | while i < len(leftArr) and j < len(rightArr): 30 | if leftArr[i] < rightArr[j]: 31 | result[k] = leftArr[i] 32 | k += 1 33 | i += 1 34 | elif leftArr[i] > rightArr[j]: 35 | result[k] = rightArr[j] 36 | k += 1 37 | j += 1 38 | else: 39 | result[k] = leftArr[i] 40 | k += 1 41 | result[k] = rightArr[j] 42 | k += 1 43 | i += 1 44 | j += 1 45 | 46 | 47 | while i < len(leftArr): 48 | result[k] = leftArr[i] 49 | k += 1 50 | i += 1 51 | 52 | while j < len(rightArr): 53 | result[k] = rightArr[j] 54 | k += 1 55 | j += 1 56 | return result 57 | 58 | 59 | print(mergeSort([3, 6, 1, 5, 8, 7, 2])) 60 | -------------------------------------------------------------------------------- /LeetCodePractice/Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | 117 / 117 test cases passed. 4 | Status: Accepted 5 | Runtime: 182 ms 6 | """ 7 | import sys 8 | class Solution(object): 9 | def longestCommonPrefix(self, strs): 10 | """ 11 | :type strs: List[str] 12 | :rtype: str 13 | """ 14 | if (len(strs) == 1 and strs is not ""): 15 | return ''.join(strs) 16 | elif (len(strs) == 1 and strs is ""): 17 | return "" 18 | prefix = dict() 19 | max_prefix = "" 20 | max_len = -sys.maxint 21 | strNum = 0 22 | for str in strs: 23 | strNum = strNum + 1 24 | 25 | for i in range(1, len(str) + 1): 26 | temp = str[0:i] 27 | 28 | if (prefix.get(temp, -1) == -1): 29 | prefix[temp] = list() 30 | prefix[temp].append(strNum) 31 | 32 | else: 33 | if (strNum not in prefix[temp]): 34 | prefix[temp].append(strNum) 35 | 36 | for (k,v) in prefix.items(): 37 | if (len(v) == strNum): 38 | #print " Probable k=",k 39 | if (len(k) > max_len): 40 | max_prefix=k 41 | max_len=len(k) 42 | 43 | return max_prefix 44 | 45 | s = Solution() 46 | print s.longestCommonPrefix(["a"]) 47 | print s.longestCommonPrefix(["abc", "abcdeflmn", "abcdef", "abcd", "abc"]) 48 | 49 | 50 | -------------------------------------------------------------------------------- /Leetcode_Challenge/Oct 15/Valid Word Square.py: -------------------------------------------------------------------------------- 1 | """ 2 | 422. Valid Word Square 3 | 4 | 33 / 33 test cases passed. 5 | Status: Accepted 6 | Runtime: 129 ms 7 | """ 8 | class Solution(object): 9 | def validWordSquare(self, words): 10 | """ 11 | :type words: List[str] 12 | :rtype: bool 13 | """ 14 | k_dummy = max(len(i) for i in words) 15 | k = max(len(words), k_dummy) 16 | 17 | for i in range(k): 18 | row = words[i] 19 | col = [] 20 | for j in range(len(words)): 21 | #print " At j = ", j, "len = ", len(words[j]), " i = ", i 22 | if (i < len(words[j])): 23 | #print " Re" 24 | col.append(words[j][i]) 25 | col = "".join(col) 26 | #print " Comparing row = ", row, " and col = ", col 27 | if (row == col): 28 | continue 29 | else: 30 | return False 31 | return True 32 | 33 | if __name__ == "__main__": 34 | sol = Solution() 35 | print sol.validWordSquare([ 36 | "ball", 37 | "area", 38 | "read", 39 | "lady" 40 | ]); 41 | 42 | print sol.validWordSquare([ 43 | "abcd", 44 | "bnrt", 45 | "crm", 46 | "dt" 47 | ]); 48 | 49 | print sol.validWordSquare([ 50 | "abcd", 51 | "bnrt", 52 | "crmy", 53 | "dtye" 54 | ]); -------------------------------------------------------------------------------- /Zookeeper/basics_kazoo.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | from kazoo.client import KazooClient 4 | import thread 5 | import time 6 | 7 | zoo_path = '/MyPath' 8 | 9 | def create_path(): 10 | zk.ensure_path(zoo_path) 11 | 12 | def create_child(num): 13 | zk.ensure_path(zoo_path + '/NodeChild' + str(num)) 14 | return 15 | 16 | def delete_child(num): 17 | zk.delete(zoo_path + '/NodeChild' + str(num)) 18 | return 19 | 20 | zk = KazooClient(hosts='localhost:2181') 21 | zk.start() 22 | 23 | create_path() 24 | 25 | #apply watch and then start thread 26 | 27 | 28 | def modify_child_in_path(threadName): 29 | 30 | print "inside thread: ", threadName 31 | k = 1 32 | while k < 10: 33 | print "creating child k : ", k 34 | create_child(k) 35 | k = k + 1 36 | time.sleep(1) 37 | 38 | k = 9 39 | while k > 0: 40 | print "deleting child k : ", k 41 | delete_child(k) 42 | k = k - 1 43 | time.sleep(1) 44 | 45 | def watch_path(threadName): 46 | 47 | print "inside thread: ", threadName 48 | 49 | @zk.ChildrenWatch(zoo_path) 50 | def child_watch_func(children): 51 | print "Inside watch function" 52 | print "List of Children %s" % children 53 | 54 | 55 | thread.start_new_thread( watch_path, ("Thread-2", ) ) 56 | time.sleep(5) 57 | print "Starting modify path call" 58 | thread.start_new_thread( modify_child_in_path, ("Thread-1", ) ) 59 | 60 | time.sleep(10000) 61 | 62 | print "END" 63 | -------------------------------------------------------------------------------- /LeetCodePractice/582. Kill Process.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | """ 4 | 166 / 166 test cases passed. 5 | Status: Accepted 6 | Runtime: 292 ms 7 | Better than 92% 8 | """ 9 | # Follow DFS approach to delete the children 10 | class Solution(object): 11 | 12 | def formDictionaries(self, pid, ppid): 13 | 14 | parent = dict() 15 | for idx in range(len(ppid)): 16 | _p = ppid[idx] 17 | if _p in parent: 18 | parent[_p].append(idx) 19 | else: 20 | parent[_p] = [idx] 21 | return parent 22 | 23 | def killProcess(self, pid, ppid, kill): 24 | """ 25 | :type pid: List[int] 26 | :type ppid: List[int] 27 | :type kill: int 28 | :rtype: List[int] 29 | """ 30 | parent = self.formDictionaries(pid, ppid) 31 | print parent 32 | node_to_delete_idx = pid.index(kill) 33 | 34 | result, stack = [], [node_to_delete_idx] 35 | while stack: 36 | popped = stack.pop() #this is the idx and not the node itself 37 | if popped is None: 38 | continue 39 | node = pid[popped] 40 | result.append(node) 41 | 42 | if node in parent: 43 | stack += parent[node] 44 | print "Stack updated: ", stack 45 | return result 46 | 47 | s=Solution() 48 | assert s.killProcess([1], [0], 1) == [1] 49 | assert( s.killProcess([1, 3, 10, 5], [3, 0, 5, 3], 5) == [5, 10]) -------------------------------------------------------------------------------- /LeetCodePractice/Find All Numbers Disappeared in an Array.py: -------------------------------------------------------------------------------- 1 | """ 2 | 4 / 4 test cases passed. 3 | Status: Accepted 4 | Runtime: 32 ms 5 | """ 6 | 7 | """ 8 | For FindDuplicates 9 | 27 / 27 test cases passed. 10 | Status: Accepted 11 | Runtime: 885 ms 12 | """ 13 | 14 | class Solution(object): 15 | def findDisappearedNumbers(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: List[int] 19 | """ 20 | if (len(nums) == 0): 21 | return [] 22 | max_num=len(nums) 23 | checker = 0 24 | result = [] 25 | for i in range(len(nums)): 26 | checker = checker | 1< 0): 30 | continue 31 | else: 32 | result.append(i) 33 | return result 34 | 35 | def findDuplicates(self, nums): 36 | """ 37 | :type nums: List[int] 38 | :rtype: List[int] 39 | """ 40 | result = [] 41 | if (len(nums) == 0): 42 | return [] 43 | checker = 0 44 | for i in range(len(nums)): 45 | if ((checker & (1< 0): 46 | result.append(nums[i]) 47 | checker = checker | 1< 0 else 'L' 45 | for f in force) 46 | # return "".join('.' if force[i] == '0' else 'R' if force[i] > 0 else 'L' for i in range(N)) 47 | 48 | s=Solution() 49 | print(s.pushDominoes("RL")) 50 | print(s.pushDominoes("R.L")) 51 | print(s.pushDominoes("R.......L")) 52 | -------------------------------------------------------------------------------- /HackerRankProblems/Balanced Brackets.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | #!/bin/python 4 | 5 | import sys 6 | 7 | def isclosebracket(bracket): 8 | if (bracket == ')' or bracket == ']' or bracket == '}'): 9 | return True 10 | return False 11 | 12 | def isopeningbracket(bracket): 13 | if ((bracket == '(' or bracket == '[' or bracket == '{')): 14 | return True 15 | return False 16 | 17 | def isTopMatching(arr, bracket): 18 | if (len(arr) == 0): 19 | return False 20 | ele = arr.pop(-1) 21 | #print " Element popped: ", ele 22 | if (ele == '(' and bracket == ')'): 23 | return True 24 | if (ele == '[' and bracket == ']'): 25 | return True 26 | if(ele == '{' and bracket == '}'): 27 | return True 28 | 29 | return False 30 | 31 | def checkifbalanced(s): 32 | if (s is None): 33 | return True 34 | arr = list() 35 | 36 | if (isclosebracket(s[0]) and len(arr) ==0 ): 37 | return False 38 | 39 | for i in range(0, len(s)): 40 | if (isopeningbracket(s[i])): 41 | arr.append(s[i]) 42 | #print "Arr", arr, " at i = ", i 43 | elif (isclosebracket(s[i]) and isTopMatching(arr, s[i])): 44 | continue 45 | else: 46 | return False 47 | 48 | if (len(arr) == 0): 49 | return True 50 | return False 51 | 52 | t = int(raw_input().strip()) 53 | for a0 in xrange(t): 54 | s = raw_input().strip() 55 | print "YES" if checkifbalanced(s) else "NO" -------------------------------------------------------------------------------- /Leetcode_Challenge/Aug 27/Elimination Game.py: -------------------------------------------------------------------------------- 1 | import numbers 2 | def call_func(n): 3 | nList = list() 4 | for x in range(1, n+1): 5 | nList.append(x) 6 | #print nList 7 | 8 | removeStart = True; 9 | while len(nList) != 1: 10 | if (removeStart): 11 | nList = nList[1::2] 12 | #print nList 13 | removeStart = False 14 | else: 15 | if (len(nList) % 2 != 0): #ODD 16 | nList = nList[1::2] 17 | #print nList 18 | else: #even 19 | nList.reverse(); 20 | nList = nList[1::2]; 21 | nList.reverse() 22 | #print nList 23 | removeStart = True 24 | return nList[0] 25 | 26 | 27 | def new_Calc(n): 28 | if n == 1: 29 | return 1; 30 | elif ( n == 2 or n == 3 or n == 4 or n ==5 ): 31 | return 2; 32 | elif (n == 6 or n == 7): 33 | return 4 34 | else: 35 | if (n % 2 != 0): #Odd 36 | n = n-1 37 | 38 | seed = 8 39 | notfound = True; 40 | while (seed < n): 41 | seed = seed + 4 42 | #print "seed = ", seed 43 | if (seed == n): 44 | return 6; 45 | else: 46 | return 8; 47 | 48 | if __name__=='__main__': 49 | #n = int(raw_input('')) 50 | #call_func(int(n)) 51 | for i in range(10, 100): 52 | print i, " --> ", call_func(int(i)) 53 | 54 | #print (new_Calc(int(n))) 55 | 56 | 57 | -------------------------------------------------------------------------------- /GeneralPractice/1282. Group the People Given the Group Size They Belong To.py: -------------------------------------------------------------------------------- 1 | __author__ = 'deepika' 2 | 3 | 4 | """ 5 | Runtime: 52 ms, faster than 99.76% of Python online submissions for Group the People Given the Group Size They Belong To. 6 | Memory Usage: 12.6 MB, less than 99.06% of Python online submissions for Group the People Given the Group Size They Belong To. 7 | 8 | Important thing is to form groups. 9 | """ 10 | class Solution(object): 11 | 12 | def _form_groups(self, array, size): 13 | results = [] 14 | 15 | i = 0 16 | while i < len(array): 17 | results.append( array[i : i + size]) 18 | i += size 19 | 20 | return results 21 | 22 | def groupThePeople(self, groupSizes): 23 | """ 24 | :type groupSizes: List[int] 25 | :rtype: List[List[int]] 26 | """ 27 | 28 | dictionary = dict() 29 | for i in range(len(groupSizes)): 30 | if groupSizes[i] not in dictionary: 31 | dictionary[groupSizes[i]] = [] 32 | dictionary[groupSizes[i]].append(i) 33 | 34 | results = [] 35 | for k,v in sorted(dictionary.items()): 36 | if len(v) <= k: 37 | results.append(v) 38 | else: 39 | results.extend(self._form_groups(v, k)) 40 | 41 | return results 42 | 43 | s=Solution() 44 | print(s.groupThePeople([3,3,3,3,3,1,3])) # [[5],[0,1,2],[3,4,6]] 45 | print(s.groupThePeople([2,1,3,3,3,2])) #[[1], [0, 5], [2, 3, 4]] 46 | 47 | --------------------------------------------------------------------------------