Step-By-Step Implementation: Change the given number into a binary and store it in string s. Run loop n times. Run another loop for string length s to convert 0 to “01” and 1 to “10” and store in a temporary string s1. After completion of each iteration, assign string s1 to s. Finally, return the value of the kth index in string s.
2 questions asked
- Question 1
The idea is to avoid generating the full binary string after each iteration, since its size doubles every time. Instead, we identify the original bit in m that gives rise to the k-th character after n iterations. The key observation is that the number of bit flips in a path from root to k-th character is equal to the number of set bits in offset, and parity of this count decides the final bit.
Answer 1// C# Code to find kth character after // n iterations using System; class GfG { // Function to count number of set // bits (used to compute parity) static int countSetBits(int x) { int cnt = 0; while (x > 0) { cnt += x & 1; x >>= 1; } return cnt; } // Function to find the k-th character // after n iterations static char KthCharacter(int m, int n, int k) { int[] binary = new int[32]; for (int i = 0; i < 32; i++) { binary[i] = (m >> i) & 1; } int totalBits = 0; // Count number of bits in m (from MSB) for (int i = 31; i >= 0; i--) { if (binary[i] == 1) { totalBits = i + 1; break; } } int blockLength = 1 << n; int blockIndex = (k - 1) / blockLength; int offset = (k - 1) % blockLength; // If m has fewer bits than blockIndex, bit is 0 int root = (blockIndex < totalBits) ? binary[totalBits - blockIndex - 1] : 0; int flips = countSetBits(offset); // Flip if parity is odd if (flips % 2 == 0) { return root == 1 ? '1' : '0'; } else { return root == 1 ? '0' : '1'; } } static void Main() { int m = 5, n = 2, k = 5; Console.WriteLine(KthCharacter(m, n, k)); } }
- Question 2
Given a stream of integers represented as arr[]. For each index i from 0 to n-1, print the multiplication of the largest, second largest, and third largest element of the subarray arr[0...i]. If i < 2 print -1.
Answer 2Steps to implement the above idea: Initialize a max-heap to track the largest elements and a result list for storing outputs. Traverse the input array and push each element into the max-heap. If the heap size is less than 3, append -1 to the result list. When the heap size is at least 3, extract the three largest elements from the heap. Calculate the product of these three elements, append it to the result list, and push them back into the heap. Finally, return or print the result list containing the outputs.