Sunteți pe pagina 1din 11

array problems

rotate a one-dimentional array of n elements left by i positions,


for example, n = 8,
arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };

i = 3,
array now becomes,
arr[8] = { 4, 5, 6, 7, 8, 1, 2, 3 };

the code shud be optimal

second problem,

for a sorted array which is rotated as given in problem one,

find the pivot value, in log(n ) time,

third proble,

for a sorted array which is rotated as given in problem one,

find a given number is there in this array or not,

time complexity log( n )

u r given a square matrix,

write a program to print it spirally,

VARIATION:
for an input value N generate a matrix, havin the elements from 1 to N*N,
without using ne external storage for storing the values from 1 to N*N,

suppose the input is , 3


the output shud be,

123
456
789

nd dont use an array for storing the values ,

another variation
now for input value 3 ,

make spiral

like

789
6 12
5 4 3

implement a queue using two stacks such that insertion and deletion
are in O(1) time

implement a stack in which push, pop and find_min all 3 operations take O(1 ) time .

One possible solution

use the structure

struct {
int value;
int min_index;
} arr;

struct data_structure {
int top;
struct arr[20];
} a;

for inserting first value,


simply put a.arr[top].value = input_value;
a.arr[top].min_index = top;
for next values
compare next input value with the value at value at the top's
min_index,
if less simply put its min_index = its index,
else
put its min_index = top's min_index

Solve this
can u print any string wthout using " " in printf function?
without using " " anywhere in the program

e.g.:
#include <stdio.h>

int main()
{
char a[6] = {'h', 'e', 'l', 'l', 'o', '\0'};
printf(a);
return 0;
}

Simple One!!
You're given an array of integers. Rearrange the
array so that all even numbers come in the begining
and odd numbers come in the end. There are no
constraints on algorithm but come up with optimized
solution. (less space and time complexity)

One possible solution


Algorithm

top = 0;
pos = 0;
while (pos <= size - 1) {
if (a[pos] % 2 == 0) {
temp = a[pos];
a[pos] = a[top];
a[top] = temp;
top++;
}
pos++;
}

tree problems
given inorder and preorder traversal of a tree make that tree,

given inorder and postorder traversal of a tree , make the tree,

given preorder and postorder traversal of a tree, how many trees are there for this
combination

make all the trees given preorder and postorder traversal of a tree

linked list problems


u r given a linked list , how wiil u detect thr is a loop or not,

u r given a linked list having a loop , ( may not be cyclic ),


how will u break the loop

minimum number of traversal required to break the loop

u r given two linked lists , such that they merge at the end,
wat is the best possible way to detect it

some interesting problems


given a number , set its least significant 1 bit to zero,

given an unsigned number , set its most significant 1 bit to zero

First prob: setting least significant bit of a number (say n)


n=n&(n-1);
2nd prob sol
the working program
#include "stdio.h"

int main (void )


{
unsigned int number;
unsigned int temp;

printf("\n:enter the value");


scanf("%u",&number );

temp = number;

temp = ( temp >> 1 | temp >> 2 ) ;


temp |= temp >>2;
temp |= temp >>4;
temp |= temp >>8;
temp |= temp >>16;

printf("\n:the output is:%u",(temp & number ) );


}
another interesting problem
rite a function such that it returns 0x00000000 if input is 0 else it returns 0xFFFFFFFF,
no if, else, loops, ternary operators,

u can use +,-,!,~,^,|,&,<<.>> operators

VARIATION:
now use only bitwise operators

solution
#include <stdio.h>

int func(int inp)


{
inp |= inp >>1;
inp |= inp >>2;
inp |= inp >>4;
inp |= inp >>8;
inp |= inp >>16;
inp |= inp <<1;
inp |= inp <<2;
inp |= inp <<4;
inp |= inp <<8;
inp |= inp <<16;

return inp;
}

int main()
{
int inp = 0;
printf("\nIN = %d, OUT = %x", inp, func(inp));

inp = 10;
printf("\nIN = %d, OUT = %x", inp, func(inp));

inp = 1;
printf("\nIN = %d, OUT = %x", inp, func(inp));

inp = 0x8000000;
printf("\nIN = %x, OUT = %x", inp, func(inp));

return 0;

u have 3 containers having capcity 20lt , 13lt, nd 6lt,

initial configuration

20lt ( 0 ) 13lt ( 13 ) 6lt ( 6 )

final configuration

20lt ( 10 ) 13lt ( 9 ) 6lt ( 0 )

20lt 13lt 6lt


_______________________________
0 13 6
6 13 0
6 7 6
12 7 0
12 1 6
18 0 1
5 13 1
5 8 6
11 8 0
11 2 6
17 2 0
17 0 2
4 13 2
4 9 6
10 9 0

another one
3 jugs,

having capacity 15 , 10 nd 6lt

initial configuration

15 ( 15 ) 10 ( 0 ) 6(0)

final configuration

15(0 ) 10 ( 8 ) 6(5)

15 10 6
----------------------------
15 0 0
5 10 0
5 4 6
11 4 0
11 0 4
1 10 4
1 8 6
7 8 0
7 2 6 - remove 2
7 6 0
1 6 6
1 10 2
11 0 2
11 2 0
5 2 6
5 8 0
0 8 5

Find the 10-digit number f0 f1 f2 f3 f4 f5 f6 f7 f8 f9


Clearly all fi belongs to 0 to 9 as they simply digit of number.
On the same time fi is frequency of digit i in the 10-digit number.
Find the property of fi?
Find the number?

"If you're familiar with the ? operator x ? y : z


you want to implement that in a function: int cond(int x, int y, int z); using
only ~, !, ^, &, +, |, <<, >> no if statements, or loops or anything else, just
those operators, and the function should correctly return y or z based on
the value of x. You may use constants, but only 8 bit constants. You can
cast all you want. You're not supposed to use extra variables, but in the
end, it won't really matter, using vars just makes things cleaner. You should
be able to reduce your solution to a single line in the end though that
requires no extra vars."

only bitwise operators and + and = and cast


int fun(int a, int b, int c)
{
a|=a>>1;
a|=a>>2;
a|=a>>4;
a|=a>>8;
a|=a>>16;

a|=a<<1;
a|=a<<2;
a|=a<<4;
a|=a<<8;
a|=a<<16;

return (~a & b) + ( (unsigned int)a & c) ;


}
another solution
(!!a)*b + (!a)*c )

C puzzle
a one line C statement to reverse the bits of a byte.
suppose byte is 11000001 then the reverse is 10000011
n=n^0xf

find the repeated value


u r given an array of numbers ( size of n ),
which has the numbers in the range 1 to n ,
thr is one element which is missing in this array and one element which repeats itself,

find the missing as well as repeated value,

time complexity O(n),


space complexity O(1)

Solution
Let the number missing be 'a' & repeated be 'b'
Get sum of all numbers of the array = n(n+1)/2 - a +b
subtract sum of first 'n' natural numbers = b- a

now calculate the sum of squares = sum of squares of 'n' natural number + b^2 - a^2
similarly subtract sum of suares of first n natural numbers....

now u hv value of b-a & b^2 - a^2

divide & u'll get b+a

so now u can calculated 'b' & 'a'

This is solved in space complexity O(1) & time (n)


:-)
ariation 1.2
now suppose that ne number may repeat ne number of times ,
u have to find the first number which repeats itself in this array,

for range 10 ,

supppose the array is

{ 4, 3, 1, 6, 4, 1, 3, 3, 3, 8 }

output shud be 4

puzzle
Find the number such that if we put last digit to the first place it will becomes twice.
I mean if number be a........mn than new number be na.......m and it will be twice of
previous. where a,b,....m,n are all digits
not all a,b,..m,n are zero. I mean at least one is non-zero.

Another approach..Simpler one


start with any number
lets take 9 for example
multiply it by 2 ...you wil get 8....write 8 & keep 1 carry
now multiply 8 by 2....16+1...17.....write 7 & keep 1 carry...

Repeat this process until u get "9" (i.e the same number u started with) dont write this
number(9) n This is ur desried number:-)
You can get more numbers similarly

Ps:- u should not start with '1' or '0' coz of obvious reasons :-)

Compare two numbers A and B and return " A is greated" or "B is greater" or " Both are equal"
You donot have to use
1. Donot use if, if-else, switch-case
2. Conditional operator ,ternary operator
3. Any loop statement
4. no relational operator

#include <stdio.h>

int main(int argc, char** argv)


{
int a, b, c = 1<<(sizeof(int)*8 -1);

a = atoi(argv[1]);
b = atoi(argv[2]);

(a-b) || printf("Equal");
((a-b) & c) && printf("a<b");
((b-a) & c) && printf("a>b");
printf("\n");
}

Problem:

Given an array having n integers. Write a prog to find the first number for which there exists
another number whose sum is a given number. For example

A[]= { 2, 7, 5, 0, 12, 10, 8 }


If given number is 15 then the first pair to sum of 15 is 7 and 8.

Problem
Array of size N is given, N is even. In this array one entry is repeated
n/2 times and the remaining n/2 entries are unique. Write algo to find
the repeated value.

time complexity O(n)


space complexity O1)

Suggested Sol:
If and n are same then here is solution in O(n/2)

1)make pairs like,a[0] and a[1], a[2] and a[3] and so on as length is even.let that repeated
value be x
2) compare two elements in each pair, if any pair has two element as same ie x then , that x is
found,
hence value is identified in O(n/2),

worst case: x is still not found.


3)then it means each pair contains one element as x, compare any two pairs, as a[0] with
a[2], a[0] with a[3], then a[1] with a[2] and a[1] with a[3], now u'll definitely get x,

hence soln. is of O(n/2) + C.


where C=4 in worst case.

Problem
design an algo for checking whether two given words are anagrams i.e. whether one word can
be obtained by permuting the letters of the other ( the words tea and eat are anagrams ).
Keep in mind that the words may contain multiple occurances of the same letter.

if anybody has ne idea abt the specific algorithm for this purpose,
than plz reply or what keywords i shud use to get it on internet.

Solution
1)
You can find anagram.c file In the internet.
http://orion.math.iastate.edu/burkardt/c_src/anagram/anagram.c

2)
Use something like a bucket sort..
take two arrays of 26 int's say a[] and b[], loop through the char array , for each letter
increment the appropriate index (for 'a' increment a[0] if occurring in 1st word or increment
b[0] if occurring in second word).

This complete exercise is done in 'n' time.

Now loop through both the arrays checking if a[i]==b[i] , exit at the first failure and declare
that words are not anagrams.

maximum time taken is 26 iterations.


Total time is O(n+26) i.e. O(n)
space is constant at O(26*2), i.e. O(1).

Seems too easy, I might have made a blunder here :))


if you have mixed cases and/or spl characters only the constants increase and over all space
and time complexity remain constant.

Problem

Given a binary tree and two node pointers of that tree, find out the closest common ancestor
of two nodes.

Solutioin

Take InOrder traversal of the tree.


check where the two specified nodes exists, both will either be on different side of root or to
the same side of root.
If both are to the different side of root, current root is the common ancestor of both.
If both are in the right half of the root, call the above procedure for right half. New root is right
child of previous root.
else recurse for left half..........

At any stage if found that root is one of the node, give ancestor as root itself.(or may be parent
of root)

Problem

Write an algorittm to find the first non-repeating character in a null


terminating string. Should be O(n)
time.

Solution:
Hashing the seen charaters may be one way of solving this problem.[
Eachtime we see a character, will increment its count. the character
with has count 1 and apper first in the string will be the result]
Is there anyother way of solving this problem in O(n) time
complexity???
Problem:

how can u detect loop in a binary tree

Solution:

one possible solution


this is the implementation of "tortoise and hare algorithm"

do level order traversal with 2 pointers and maintainin two queues,


move one pointer with double the speed of other.

S-ar putea să vă placă și