### 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 … More Palindrome String Check With Non-alphanumeric Characters

### 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[0] 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 … More Stocks Maximize Profit, Multiple Buy & Sell

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[0] 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 … More Stock Buy-Sell Maximize Profit

### 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 … More Intersection of Two Linked Lists

### 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 … More Majority Element in a List

### 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 … More Python Solution: House Robber Problem

### 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, … More Palindrome Linked Lists O(1) Space Solution