Posts

Hamming Distance LeetCode

 The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them. Example 1: Input: x = 1, y = 4 Output: 2 Explanation: 1   (0 0 0 1) 4   (0 1 0 0)        ↑   ↑ The above arrows point to positions where the corresponding bits are different. Example 2: Input: x = 3, y = 1 Output: 1 Approach 1: - class Solution {     public int hammingDistance ( int x , int y ) {                 int count = 0 ;         // Convert integer x to a 32-bit binary string with leading zeros         String a = String . format ( "%32s" , Integer . toBinaryString (x)). replace ( ' ' , '0' );         // Convert integer y to a 32-bit binary string with leading zeros         String b = String . format ( "%...

Check whether an Array can be made 0 by splitting and merging repeatedly

 Check whether an Array can be made 0 by splitting and merging repeatedly Given an array arr[] with N elements, the task is to find whether all the elements of the given array can be made 0 by given operations. Only 2 types of operations can be performed on this array: Split an element B into 2 elements C and D such that B = C + D. Merge 2 elements P and Q as one element R such that R = P^Q i.e. (XOR of P and Q). You have to determine whether it is possible to convert array A to size 1, containing a single element equal to 0 after several splits and/or merges? Input: arr = [9, 17] Output: Yes Explanation: Following is one possible sequence of operations – 1) Merge i.e 9 XOR 17 = 24 2) Split 24 into two parts each of size 12 3) Merge i.e 12 XOR 12 = 0 As there is only 1 element i.e 0. So, it is possible. Input: arr = [1] Output: No public class codefile {     static boolean check ( int []  input ){           int i , ctr = 0 ;   ...

29. Divide Two Integers LeetCode

Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. Return the quotient after dividing dividend by divisor. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.   Example 1: Input: dividend = 10, divisor = 3 Output: 3 Explanation: 10/3 = 3.33333.. which is truncated to 3. Example 2: Input: dividend = 7, divisor = -3 Output: -2 Explanation: 7/-3 = -2.33333.. which is truncated to -2. class Solution {     public int divide ( int dividend , int divisor ) {         // Handle overflo...

Find Peak Element leetCode

 A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. class Solution {     public int findPeakElement ( int [] nums ) {         int left = 0 ;         int right = nums . length - 1 ;         while (left ...

Single Element in a Sorted Array LeetCode

 You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return the single element that appears only once. Your solution must run in O(log n) time and O(1) space. Example 1: Input: nums = [1,1,2,3,3,4,4,8,8] Output: 2 Example 2: Input: nums = [3,3,7,7,10,11,11] Output: 10   class Solution {     public int singleNonDuplicate ( int [] nums ) {         int start = 0 ;         int end = nums . length - 1 ;         // Binary search loop - keep narrowing the range until we find the single element         while (start < end) {             // Calculate mid index safely to avoid overflow             int mid = start + (end - start) / 2 ;             // Check if mid and mid+1 are a pair (same number) ...

33. Search in Rotated Sorted Array LeetCode

 There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Example 3: Input: nums = [1], target = 0 Output: -1 Approach 1 : class Solution {     public int search ( int [] nums , int target ) {                 int n = nums . length ;     ...

find the number of trailing zeroes

 Given an integer N, the task is to find the number of trailing zeroes in the binary representation of the given number. Input 1: N = 12 Output 1: 2 Explanation 1: The binary representation of the number 13 is “1100”. Therefore, there are two trailing zeros in the 12. Input 2: -56 Output 2: 3 Approach 1 : Use Inbuilt function int trailingZeroCount = Integer.numberOfTrailingZeros(n);  Aprroach 2: public class codefile {     static int solve ( int n ){       // Method to count the number of trailing zeros in the binary representation of 'n'                 // Initialize count to 0         int count = 0 ;         // Loop to check each bit from the right (Least Significant Bit)         // Use 'n & 1' to check if the current bit is 0 (last bit)         // Shift the number to the right using >>> (unsigned right shift) to...

190. Reverse Bits LeetCode

 Reverse bits of a given 32 bits unsigned integer. Note: Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.   Example 1: Input: n = 00000010100101000001111010011100 Output:    964176192 (00111001011110000010100101000000) Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000. Example 2: Input: n = 11111111111111111111111111111101 Output:   3221225471 (10111111111111...

34. Find First and Last Position of Element in Sorted Array leetCode

 Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1] Example 3: Input: nums = [], target = 0 Output: [-1,-1] C++: class Solution { public:     vector < int > searchRange ( vector < int > & nums , int target ) {         vector< int >result;         int firstIndex= firstOcc (nums,target);         int lastIndex = lastOcc (nums,target);         result . push_back (firstIndex);         result . push_back (lastIndex);         return result;             }     int firstOcc (...

693. Binary Number with Alternating Bits LeetCode

 Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.   Example 1: Input: n = 5 Output: true Explanation: The binary representation of 5 is: 101 Example 2: Input: n = 7 Output: false Explanation: The binary representation of 7 is: 111. Example 3: Input: n = 11 Output: false Approach 1: class Solution {     public boolean hasAlternatingBits ( int n ) {                 String binary = Integer . toBinaryString (n);         for ( int i = 1 ;i< binary . length ();i++)         {             if ( binary . charAt (i) == binary . charAt (i- 1 ))             {                 return false ;             }         }         return true ;   ...