Saturday, June 25, 2016

Today we practice a few more coding questions:
Given two rectangles, find whether they are overlapping or not?
static bool intersects(Rectangle r1, Rectangle r2)
{
bool isdisjoint = false;
// are  they disjoint along x axis ?
if (r1.tl.x < r2.tl.x)
   isdisjoint = r1.br.x < r2.tl.x;
else
  isdisjoint = r2.br.x < r1.tl.x;
if (isdisjoint == true) return false;

// are they disjoint along y-axis ?
if (r1.br.y < r2.br.y)
   isdisjoint = r1.tl.y < r2.br.y;
else
  isdisjoint = r2.tl.y < r1.br.y;
return isdisjoint == false;
}

Given a String s and int r , first fill each character row wise and print column wise.
for e.g. String s = “abcdefgh” and r = 3
so filling column wise would give :
a d g
b e h
c f
and final answer would be adgbehcf.
string GetRearranged(string s, int r)
{
var ret = new stringbuilder(s.length);
int start = 0;
int k = 0;
for (int i = 0; i < s.length; i++)
{
if (start + k*r) < s.length){
     ret[i] = s[start + k * r];
     k = k + 1;
}else{
     k = 0;
     start++;
     ret[i] = s[start + k * r];
     k = k + 1;
}
}
return ret.toString();
}

3) Node findLCAInBT(Node root, int n1, int n2, ref bool v1, ref bool v2)
{
if (root == null) return null;
if (root.key == n1) {
v1 = true;
return root;
}
if (root.key == n2){
v2 = true;
return root;
}
var left = findLCAInBT(root.left, n1, n2, ref v1, ref v2);
var right = findLCAInBT(root.right, n1, n2, ref v1, ref v2);
if (left && right) return root;
if (left != null) return left;
else return right;
}
if ( v1  && v2 || v1 && find(lca, n2) || v2 && find(lca,n1))
     return lca;

4) Implement k stacks in an array
Use the following auxiliary data structures
an array to store the top of all k stacks. This is initialized to -1 for each stack
an array to store the next element index for all n elements. This is initialized to the next element for all but the last
a free variable pointing to the first available slot. This is initialized to the first one (free = 0)
void push(int val, int k-at-i)
{
//check for overflow and then
int i = free;
free = next[i];
next[i] = top[sn];
top[k-at-i] = i;
arr[i] = item;
}

void pop(int k-at-i)
{
//check for underflow and then
int i = top[k-at-i];
top[k-at-i] = next[i]
nex[i] = free;
free = i;
return array[i];
}

No comments:

Post a Comment