development

Intersection of Two Linked Lists

# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): “”” :type head1, head1: ListNode :rtype: ListNode “”” lenA, lenB = 0, 0 curA, curB = headA, headB while curA: lenA += 1 curA = curA.next while curB: lenB […]

Read more
development

Majority Element in a List

Solution using Moore’s Voting Algorithm class Solution(object): def majorityElement(self, nums): “”” :type nums: List[int] :rtype: int “”” current = nums[0] freq = 1 for i in range(1, len(nums)): if current is None: current = nums[i] freq = 1 continue if nums[i] == current: freq += 1 else: freq -= 1 if freq == 0: current […]

Read more
development

Rotate an Array using Constant Space

class Solution(object): def reverse(self, start, end, nums): while start < end: nums[start], nums[end] = nums[end], nums[start] start += 1 end -= 1 def rotate(self, nums, k): “”” :type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. “”” if len(nums) == 0: return nums k = k % len(nums) […]

Read more
development

Python Solution: House Robber Problem

class Solution(object): def __init__(self): self.maxVal = 0 self.lookup = {} def rob(self, nums): “”” :type nums: List[int] :rtype: int “”” if len(nums) == 0: return 0 if len(nums) == 1: return nums[0] if len(nums) >= 2: self.lookup[0] = nums[0] self.lookup[1] = max(nums[0], nums[1]) for index in range(2, len(nums)): # There are two options at each […]

Read more
development

Palindrome Linked Lists O(1) Space Solution

There are three isolated steps: Find the mid of the list Reverse half of the list and create a new head Compare two heads class Solution(object): def findMiddle(self, head): slow = fast = head # find the mid node while fast and fast.next: fast = fast.next.next slow = slow.next if fast is None: return slow, […]

Read more
development

Palindrome LinkedList Recursive

Details Send the pointer to head(phead) and head itself. Recurse till next of head is not NULL. Start popping the frames. If *phead == *head, good to move to next frame-up. Before moving up, move phead to next // Recursive function to check if linked list is palindrome or not int checkPalindrome(struct Node** left, struct […]

Read more
development

Pascal Triangle II

def getRow(self, rowIndex): “”” :type rowIndex: int :rtype: List[int] “”” if rowIndex == 0: return [1] numRows = rowIndex + 1 previous = [1] answer = None for x in range(2, numRows+1): row = [1]*x # Mutate the row for y in range(1, x-1): #print(“x={} y={} row={} prev={}”.format(x, y, row, previous)) row[y] = previous[y-1]+ previous[y] […]

Read more