Skip to main content

Posts

Showing posts from March, 2022

Remove Linked List Elements

Remove Linked List Elements Topic : Recursion Given the  head  of a linked list and an integer  val , remove all the nodes of the linked list that has  Node.val == val , and return  the new head .   Example 1: Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5] Example 2: Input: head = [], val = 1 Output: [] Example 3: Input: head = [7,7,7,7], val = 7 Output: []   Constraints: The number of nodes in the list is in the range  [0, 10 4 ] . 1 <= Node.val <= 50 0 <= val <= 50 C++ Recursive :  class Solution { public : ListNode* removeElements(ListNode* head, int val ) { if (head == NULL){ return NULL; } if (head -> val != val ){ head -> next = removeElements(head -> next, val ); return head; } else { ListNode* newHead = head -> next; return removeElements(newHead, val ); } } }; Perfect Solution : /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(

Power of Four

Power of Four   Topic : Recursion Given an integer  n , return  true  if it is a power of four. Otherwise, return  false . An integer  n  is a power of four, if there exists an integer  x  such that  n == 4 x . bool isPowerOfFour ( int n ) { if (n<= 0 ) return false ; if (n== 1 || n== 4 ) return true ; if (n% 4 != 0 ) return false ; return isPowerOfFour(n/ 4 ); } public boolean isPowerOfFour ( int n) { return n > 1 && n % 4 == 0 ? isPowerOfFour(n/ 4 ) : n == 1 ; } class Solution: def isPowerOfFour(self, n: int) -> bool: if n == 1: return True elif n == 0: return False else: return n%4 == 0 and self.isPowerOfFour(n//4) Wondering : class Solution : def isPowerOfFour ( self, n: int ) -> bool: return n > 0 and log2(n) % 2 == 0