development

## Palindrome String Check With Non-alphanumeric Characters

class Solution(object): def isPalindrome(self, s): “”” :type s: str :rtype: bool “”” if len(s) < 1: return True start, end = 0, len(s) – 1 while start < end: # Loop till a special char is found while start < end and not s[start].isalnum(): start += 1 # Always keep the check start < end […]

development

## Stocks Maximize Profit, Multiple Buy & Sell

class Solution(object): def maxProfit(self, prices): “”” :type prices: List[int] :rtype: int “”” if len(prices) < 2: return 0 minP = prices result = 0 for price in prices: if minP == float(‘inf’): minP = price profit = (price – minP) if profit > 0: result += profit minP = float(‘inf’) minP = min(price, minP) return […]

development

class Solution(object): def maxProfit(self, prices): “”” :type prices: List[int] :rtype: int “”” if len(prices) == 0 or len(prices) == 1: return 0 minP = prices result = 0 for price in prices: # Maintain the maximum profit at each price result = max(result, price – minP) # Maintain the minimum price seen so far minP […]

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 […]

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 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 […]

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 if len(nums) >= 2: self.lookup = nums self.lookup = max(nums, nums) for index in range(2, len(nums)): # There are two options at each […]