Interview Questions | Easy | List | Leetcode

Interview Questions | Easy | List | Leetcode:

344Reverse String

 class Solution:
    def reverseString(self, s: List[str]) -> None:
        s.reverse()


136Single Number

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        check = nums[0]

        for i in nums[1:]:
            check = check ^ i
            
        return check


237Delete Node in a Linked List

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, node):
        node.val = node.next.val
        to_del = node.next
        node.next = node.next.next
        del(to_del)


46Permutations

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        from itertools import permutations
        per = list(permutations(nums))

        return per


206Reverse Linked List

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:

        root = None
        while head != None:
            root = ListNode(head.val, root)
            head = head.next

        return root


78Subsets

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        from itertools import combinations
        comb = []
        for i in range(len(nums) + 1):
             comb.append(list(combinations(nums, i)))

             ans = []
             for i in comb:
                 for j in i:
                     ans.append(j)

        return ans


412Fizz Buzz

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        ans = []
        for i in range(1, n + 1):
            if i % 15 == 0:
                ans.append("FizzBuzz")
            elif i % 3 == 0:
                ans.append("Fizz")
            elif i % 5 == 0:
                ans.append("Buzz")
            else:
                ans.append(str(i))

        return ans

Post a Comment

0 Comments