/*
* 1.Given a sorted array a and a sum k print
* all pairs of indexes i and j such that
* a[i]+a[j]=k.
*/
void printPairsWithSum(int *array, int k, int len) {
int startIndex = 0, endIndex = len - 1, sum;
while (startIndex < endIndex) {
sum = array[startIndex] + array[endIndex];
if (sum == k) {
printf("%d %d \n", startIndex, endIndex);
startIndex++;
} else if (sum > k)
endIndex--;
else
startIndex++;
}
}
int main() {
int *array = malloc(sizeof(int) * 100);
int len, i;
scanf("%d", &len);
for (i = 0; i < len; i++) {
scanf("%d ", &array[i]);
}
printPairsWithSum(array, 12, len);
return 0;
}
Showing posts with label Interview questions. Show all posts
Showing posts with label Interview questions. Show all posts
Friday, July 19, 2013
Find a pair of elements from an array whose sum equals a given number
Sunday, September 9, 2012
Stack Operations
Stack create, push, pop, empty operations
typedef struct _stack {
int top;
void* array[20];
} Stack;
Stack* createStack()
{
Stack *stack = malloc(sizeof(Stack));
memset(stack, 0, sizeof(Stack));
return stack;
}
void push(Stack* stack, void* elem)
{
stack->array[stack->top] = elem;
stack->top += 1;
}
void* pop(Stack* stack)
{
void* elem = stack->array[stack->top-1];
stack->top -= 1;
return elem;
}
void* top(Stack* stack)
{
if (stack->top == 0)
return NULL;
return stack->array[stack->top-1];
}
int isEmpty(Stack* stack)
{
return stack->top;
}
Inorder Traversal of binary tree
Inorder traversal of binary tree - Recursive
Inorder traversal of binary tree - Iterative
typedef struct _binaryTreeNode
{
struct _binaryTreeNode *left;
struct _binaryTreeNode *right;
void* object;
} TreeNode;
void inOrderTraversalRecursive(TreeNode* root) {
if (root == NULL )
return;
inOrderTraversalRecursive(root->left);
printf("%d ", *(int *) root->object);
inOrderTraversalRecursive(root->right);
}
Inorder traversal of binary tree - Iterative
void inOrderTraversalIterative(TreeNode* root) {
if (root == NULL )
return;
Stack *tempStack = createStack();
do {
while (root != NULL ) {
push(tempStack, root);
root = root->left;
}
if (isEmpty(tempStack) != 0) {
root = pop(tempStack);
printf("%d ", *((int*) root->object));
root = root->right;
}
} while ((isEmpty(tempStack) != 0) || root != NULL );
}
PS: Stack related functions are here.
Subscribe to:
Posts (Atom)