The post Linked List Components appeared first on Coddicted.

]]>We are given **head**, the head node of a linked list containing **unique integer values**.

We are also given the list **G**, a subset of the values in the linked list.

Return the number of connected components in **G**, where two values are connected if they appear consecutively in the linked list.

**Example 1:**

Input: head: 0->1->2->3 G = [0, 1, 3] Output: 2 Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.

**Example 2:**

Input: head: 0->1->2->3->4 G = [0, 3, 1, 4] Output: 2 Explanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.

**Note:**

- If N is the length of the linked list given by head, 1 <= N <= 10000.
- The value of each node in the linked list will be in the range [0, N – 1].
- 1 <= G.length <= 10000.
- G is a subset of all values in the linked list.

''' https://leetcode.com/problems/linked-list-components/ ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def numComponents(self, head, G): """ :type head: ListNode :type G: List[int] :rtype: int """ temp = head lst = [] G = set(G) li = 0 while temp: if temp.val in G: lst.append([temp.val, li]) temp = temp.next li += 1 #print lst p = lst[0] c = 1 for l in lst[1:]: if l[1] - p[1] != 1: c += 1 p = l return c

The post Linked List Components appeared first on Coddicted.

]]>The post Increasing Order Search Tree appeared first on Coddicted.

]]>Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child (Increasing order search tree).

**Example 1:**

Input: [5,3,6,2,4,null,8,1,null,null,null,7,9] 5 / \ 3 6 / \ \ 2 4 8 / / \ 1 7 9 Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] 1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9

**Note:**

- The number of nodes in the given tree will be between 1 and 100.
- Each node will have a unique integer value from 0 to 1000.

''' https://leetcode.com/problems/increasing-order-search-tree/ ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def increasingBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root: return root #print root.val if not root.left and not root.right: return root left = None if root.left: left = self.increasingBST(root.left) right = self.increasingBST(root.right) if left: x = left while x.right: x = x.right x.right = root root.right = right root.left = None root = left else: root.right = right #print "returning ", root.val return root

The post Increasing Order Search Tree appeared first on Coddicted.

]]>The post Find all Anagrams in a String appeared first on Coddicted.

]]>Given a string ** s** and a non-empty string

Strings consists of lowercase English letters only and the length of both strings * s* and

The order of output does not matter.

**Example 1:**

**Input**:

s: “cbaebabacd” p: “abc”

**Output**:

[0, 6]

**Explanation:**

The substring with start index = 0 is “cba”, which is an anagram of “abc”.

The substring with start index = 6 is “bac”, which is an anagram of “abc”.

**Example 2:**

**Input**:

s: “abab” p: “ab”

**Output**:

[0, 1, 2]

**Explanation:**

The substring with start index = 0 is “ab”, which is an anagram of “ab”.

The substring with start index = 1 is “ba”, which is an anagram of “ab”.

The substring with start index = 2 is “ab”, which is an anagram of “ab”.

''' https://leetcode.com/problems/find-all-anagrams-in-a-string/ ''' class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ l = 0 d = {} for c in p: d[c] = d.get(c,0) + 1 l += 1 i = 0 ln = 0 ds = {} res = [] for c in s: if c not in d: ds = {} ln = 0 i += 1 continue ds[c] = ds.get(c, 0) + 1 ln += 1 if ln == l: if d == ds: res.append(i-ln+1) ln -= 1 ds[s[i-ln]] -= 1 if ds[s[i-ln]] == 0: del ds[s[i-ln]] i += 1 return res

The post Find all Anagrams in a String appeared first on Coddicted.

]]>The post Custom Sort String appeared first on Coddicted.

]]>S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.

Return any permutation of T (as a string) that satisfies this property.

**Example** :

**Input**:

S = “cba”

T = “abcd”

**Output**: “cbad”

**Explanation**:

“a”, “b”, “c” appear in S, so the order of “a”, “b”, “c” should be “c”, “b”, and “a”.

Since “d” does not appear in S, it can be at any position in T. “dcba”, “cdba”, “cbda” are also valid outputs.

**Note:**

- S has length at most 26, and no character is repeated in S.
- T has length at most 200.
- S and T consist of lowercase letters only.

''' https://leetcode.com/problems/custom-sort-string/ ''' class Solution(object): def customSortString(self, S, T): """ :type S: str :type T: str :rtype: str """ d = {} for c in T: d[c] = d.get(c,0) + 1 res = "" for c in S: if c in d: res += c*d[c] del(d[c]) for key in d: res += key*d[key] return res

The post Custom Sort String appeared first on Coddicted.

]]>The post Monotonic Array appeared first on Coddicted.

]]>An array is monotonic if it is either monotone increasing or monotone decreasing.

An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].

Return true if and only if the given array A is monotonic.

**Example 1**:

**Input**: [1,2,2,3]

**Output**: true

**Example 2**:

**Input**: [6,5,4,4]

**Output**: true

**Example 3**:

**Input**: [1,3,2]

**Output**: false

**Example 4**:

**Input**: [1,2,4,5]

**Output**: true

**Example 5**:

**Input**: [1,1,1]

**Output**: true

**Note**:

- 1 <= A.length <= 50000
- -100000 <= A[i] <= 100000

''' https://leetcode.com/problems/monotonic-array/ ''' class Solution(object): def isMonotonic(self, A): """ :type A: List[int] :rtype: bool """ ln = len(A) if ln < 3: return True p = A[0] i = 0 for n in A: if p != n: break i += 1 if i == ln: return True flag = (A[i-1] <= A[i]) p = A[i] while i < ln: n = A[i] if flag: if p > n: return False else: if p < n: return False p = n i += 1 return True

The post Monotonic Array appeared first on Coddicted.

]]>The post Nth Digit in Whole Numbers appeared first on Coddicted.

]]>Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

**Note:**

n is positive and will fit within the range of a 32-bit signed integer (n < 231).

The intuition for the solution is thinking about what’s the count of numbers having d digits.

For example, there are 9 numbers (1-9) having 1 digit, 90 numbers (10-99) having 2 digits and so on.

Once we have this, we know how many digits are there in each range of numbers. Based on that we find the numbers which would have the required digit.

''' https://leetcode.com/problems/nth-digit/''' class Solution(object): def findNthDigit(self, n): """ :type n: int :rtype: int """ import math #maxInt = 2147483648 if n < 10: return n n = n - 9 # counts of integers of 1,2,3 etc. digit counts d = { 1 : 9, # not to be used. Only for reference 2 : 90, 3 : 900, 4 : 9000, 5 : 90000, 6 : 900000, 7 : 9000000, 8 : 90000000, 9 : 900000000 } i = 2 digits = i * d[i] while n > digits: n -= digits i += 1 digits = i * d[i] # Defines the number to be used div = int(math.ceil(n / float(i))) # Defines the digit within number to be used mod = n % i x = int("9" * (i-1)) # Holds the actual number which contains required digit num = x + div # Index of the digit within number index = mod - 1 return int(str(num)[index])

The post Nth Digit in Whole Numbers appeared first on Coddicted.

]]>The post Binary Watch Problem appeared first on Coddicted.

]]>A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).

Each LED represents a zero or one, with the least significant bit on the right.

For example, the above binary watch reads “3:25”.

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

**Example 1:**

**Input**: n=1

**Output**: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, “0:08”, “0:16”, “0:32”]

First thing to note about the problem is about the possible values we can have for n.

If we see the hours section of Watch, we have 4 LEDs. However, we can’t have all 4 in ON state simultaneously as it would make hour value to be more than 12 while the problem specifies hour values to be only in range 0-11.

Similarly, for minutes, we can’t have a value more than 59.

Next we need to have a way of making combinations similar to nCr (Choosing ** r** values out of given

''' https://leetcode.com/problems/binary-watch/ ''' class Solution(object): def combination(self, n, k, inp, res): # inp is expected to be a list of size n #print n,k,inp,res if k == 0: res.append([i for i in inp]) return if k > n: return #for i in range(1,n+1): inp[n-1] = 1 self.combination(n-1,k-1, inp, res) inp[n-1] = 0 self.combination(n-1, k, inp, res) def getHours(self, h): if h == 0: return ["0"] if h == 1: return ["1", "2", "4", "8"] if h == 2: return ["3", "5", "6", "9", "10"] if h == 3: return ["7", "11"] def getMinutes(self, m): inp = [0,0,0,0,0,0] res = [] self.combination(6, m, inp, res) mins = [1, 2, 4, 8, 16, 32] minutes = [] for comb in res: i = 0 mn = 0 while i < 6: if comb[i] == 1: mn += mins[i] i += 1 if mn > 59: continue if mn < 10: minutes.append("0" + str(mn)) else: minutes.append(str(mn)) return minutes def readBinaryWatch(self, num): """ :type num: int :rtype: List[str] """ i = 0 res = [] while i <= num: h = i m = num - i if h < 4 and m < 6: lh = self.getHours(h) #print lh lm = self.getMinutes(m) #print lm for hr in lh: for mn in lm: res.append(hr + ":" + mn) i += 1 return res

The post Binary Watch Problem appeared first on Coddicted.

]]>The post Leaf-Similar trees appeared first on Coddicted.

]]>Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Note:

Both of the given trees will have between 1 and 100 nodes.

''' https://leetcode.com/problems/leaf-similar-trees/ ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findLeaves(self, root, leaves): if not root.left and not root.right: leaves.append(root.val) return if root.left: self.findLeaves(root.left, leaves) if root.right: self.findLeaves(root.right, leaves) def leafSimilar(self, root1, root2): """ :type root1: TreeNode :type root2: TreeNode :rtype: bool """ leaves1 = [] leaves2 = [] self.findLeaves(root1, leaves1) self.findLeaves(root2, leaves2) i = 0 ln = len(leaves1) while i < ln and leaves1[i] == leaves2[i]: i += 1 if i < ln: return False return True

/* https://leetcode.com/problems/leaf-similar-trees/description/ */ import java.util.List; import java.util.ArrayList; public class LeafSimilarTrees { public static void main(String[] args) { TreeNode root = new TreeNode(3); root.left = new TreeNode(5); root.right = new TreeNode(1); root.left.left = new TreeNode(6); root.left.right = new TreeNode(2); root.left.right.left = new TreeNode(7); root.left.right.right = new TreeNode(4); root.right.left = new TreeNode(9); root.right.right = new TreeNode(8); LeafSimilarTrees l = new LeafSimilarTrees(); System.out.println(l.leafSimilar(root, root)); } public boolean leafSimilar(TreeNode root1, TreeNode root2) { List<Integer> a = getLeafValueSequence(root1); List<Integer> b = getLeafValueSequence(root2); System.out.println(a); System.out.println(b); return a.equals(b); } private List<Integer> getLeafValueSequence(TreeNode root) { List<Integer> list = new ArrayList<>(); helper(root, list); return list; } private void helper(TreeNode root, List<Integer> seq) { if(root == null) return; helper(root.left, seq); if(root.left==null && root.right==null) seq.add(root.val); helper(root.right, seq); } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }

The post Leaf-Similar trees appeared first on Coddicted.

]]>The post Shortest Distance to a Character appeared first on Coddicted.

]]>Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example 1:

Input: S = “loveleetcode”, C = ‘e’

Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

Note:

1. S string length is in [1, 10000].

2. C is a single character, and guaranteed to be in string S.

3. All letters in S and C are lowercase.

''' https://leetcode.com/problems/shortest-distance-to-a-character/ ''' class Solution(object): def shortestToChar(self, S, C): """ :type S: str :type C: str :rtype: List[int] """ lns = len(S) i = 0 indx = [] ln = -1 for c in S: if c == C: indx.append(i) ln += 1 i += 1 # Start populating the output i = 0 output = [] while i <= indx[0]: output.append(indx[0] - i) i += 1 j = 0 while i < indx[ln]: if indx[j+1] == i: output.append(0) j += 1 else: output.append(min(i - indx[j], indx[j+1] - i)) i += 1 while i < lns: output.append(i - indx[ln]) i += 1 return output

The post Shortest Distance to a Character appeared first on Coddicted.

]]>The post Student Attendance Record I appeared first on Coddicted.

]]>
You are given a string representing an attendance record for a student. The record only contains the following three characters:

‘A’ : Absent.

‘L’ : Late.

‘P’ : Present.

A student could be rewarded if his attendance record doesn’t contain more than one ‘A’ (absent) or more than two continuous ‘L’ (late).

You need to return whether the student could be rewarded according to his attendance record.

Example 1:

Input: “PPALLP”

Output: True

Example 2:

Input: “PPALLL”

Output: False

Example 3:

Input: “PPALLPLL”

Output: True

''' https://leetcode.com/problems/student-attendance-record-i/ ''' class Solution(object): def checkRecord(self, s): """ :type s: str :rtype: bool """ aCount = 0 #prevC = '' lateCount = 0 reward = True for c in s: if c == 'A': aCount += 1 lateCount = 0 if aCount > 1: reward = False break if c == 'L': lateCount += 1 if lateCount > 2: reward = False break else: lateCount = 0 return reward

The post Student Attendance Record I appeared first on Coddicted.

]]>