Remove duplicates from an unsorted linked list keeping only one instance

Problem Write code to remove duplicates from an unsorted linked list. FOLLOW UP: How would you solve this problem if a temporary buffer is not allowed? Examples Example 1: 2 -> 3 -> 2 -> 5 -> 2 -> 8 -> 2 -> 3 -> 8 -> null => 2 -> 3 -> 5 -> 8 -> null ...

Replace all spaces in c-style string with '%20'

Problem Write a C program that will replace all spaces with ‘%20′ Examples Input: s = "Mr John Smith" Output: "Mr%20John%20Smith Solution Method 1 - Count spaces and traverse from end The algorithm is as follows: Count the number of spaces during the first scan of the string. Parse the string again from the end and for each character: If a space is encountered, store “%20”. Else, store the character as it is in the newly shifted location. Code C void replaceSpaces(char[] str, int length) { int spaceCount = 0, newLength, i = 0; for (i = 0; i < length; i++) { if (str[i] == ' ') { spaceCount++; } } newLength = length + spaceCount * 2; str[newLength] = '\0'; for (i = length - 1; i >= 0; i--) { if (str[i] == '') { str[newLength - 1] = '0'; str[newLength - 2] = '2'; str[newLength - 3] = '%'; newLength = newLength - 3; } else { str[newLength - 1] = str[i]; newLength = newLength - 1; } } } ...

Rotate String Problem

Problem Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ? OR Assume you have a method isSubstring() which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring. OR Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. ...

Set all bits of a number in a range equal to another number

Problem You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j). Examples Example 1: Input: n = 1024, m = 21, i = 2, j = 6 Output: 1108 Explanation: n's binary representation: 10000000000 m's binary representation: 10101 output's bin represention: 10001010100 i = 2, j = 6 n = 1000| - - - - - | 00 ^ ^ 6 2 n'= 1000| 1 0 1 0 1 | 00 ...

April 3, 2022 · 4 min · TagsList of tags for the post  ctci ·  bits

Swap odd and even bits in an integer

Problem Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc). Input : An integer x Output : An integer y, which odd and even bit swapped (with 0th bit being least significant bit) Examples Example 1: Input: x = 10 = 1010 Output: 5 = 0101 (0th bit and 1st bit have been swapped,also 2nd and 3rd bit have been swapped) ...

This site uses cookies to improve your experience on our website. By using and continuing to navigate this website, you accept this. Privacy Policy