curl dm01:8082/nodes
curl -vv -X POST -d username=foo -d password=foo123 dm01:8082/login
* Adding handle: conn: 0x7fcdb980aa00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fcdb980aa00) send_pipe: 1, recv_pipe: 0
* About to connect() to dm01 port 8082 (#0)
* Trying 10.3.48.19...
* Connected to dm01 (10.3.48.19) port 8082 (#0)
> POST /login HTTP/1.1
> User-Agent: curl/7.30.0
> Host: dm01:8082
> Accept: */*
> Content-Length: 28
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 28 out of 28 bytes
< HTTP/1.1 302 Found
< Set-Cookie: session=ufvuwYxNQWg5pjvSRTUyyHA921jwffc8; Max-Age=7776000; HttpOnly
< Set-Cookie: JSESSIONID=15757nag01iw5zxzo52cayz8n;Path=/
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Set-Cookie: session=SRCdeb9kLBH5sSrWkNOQiKt4dlaeBWK2; Max-Age=7776000; HttpOnly
< Location: http://dm01:8082/
< Content-Length: 0
<
* Connection #0 to host dm01 left intact
curl -b session=ufvuwYxNQWg5pjvSRTUyyHA921jwffc8 dm01:8082/nodes
// Should work fine
Monday, January 2, 2017
curl behind Authentication
[PHP] AD/LDAP Integration
// make sure your host is the correct one
// that you issued your secure certificate to
$ldaphost = "";
$ldapport = "";
$ldapbasedn = "ou=box.net,dc=ad,dc=whirl,dc=net";
// using ldap bind
$ldaprdn = ''; // AD username
$ldappass = ''; // AD password
// connect to ldap server
$ldapconn = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to LDAP server.");
if ($ldapconn) {
// binding to ldap server
@ldap_bind($ldapconn, 'AD\\'.$ldaprdn, $ldappass) or die('Could not bind to AD');
// verify binding
if ($ldapconn) {
$attributes_ad = array("sAMAccountName", "displayName","description","cn","givenName","sn","mail","co","mobile","company");
$search = ldap_search($ldapconn, $ldapbasedn, "(sAMAccountName=$ldaprdn)", $attributes_ad) or die ("Error in search query");
$result = ldap_get_entries($ldapconn, $search);
print_r($result);
echo PHP_EOL;
} else {
echo "LDAP bind failed..." . PHP_EOL;
}
}
Wednesday, November 9, 2016
[PHP] Implement Binary Tree
class Node
{
public $value, $left, $right;
public function __construct($value)
{
$this->value = $value;
}
}
Search:
class BST
{
public $root;
public function __construct($value = null)
{
if ($value !== null) {
$this->root = new Node($value);
}
}
public function search($value)
{
$node = $this->root;
while($node) {
if ($value > $node->value) {
$node = $node->right;
} elseif ($value < $node->value) {
$node = $node->left;
} else {
break;
}
}
return $node;
}
}
Insertion:
public function insert($value)
{
$node = $this->root;
if (!$node) {
return $this->root = new Node($value);
}
while($node) {
if ($value > $node->value) {
if ($node->right) {
$node = $node->right;
} else {
$node = $node->right = new Node($value);
break;
}
} elseif ($value < $node->value) {
if ($node->left) {
$node = $node->left;
} else {
$node = $node->left = new Node($value);
break;
}
} else {
break;
}
}
return $node;
}
Min:
public function min()
{
if (!$this->root) {
throw new Exception('Tree root is empty!');
}
$node = $this->root;
return $node->min();
}
public function min()
{
$node = $this;
while ($node->left) {
if (!$node->left) {
break;
}
$node = $node->left;
}
return $node;
}
Max:
public function max()
{
if (!$this->root) {
throw new Exception('Tree root is empty!');
}
$node = $this->root;
return $node->max();
}
public function max()
{
$node = $this;
while ($node->right) {
if (!$node->right) {
break;
}
$node = $node->right;
}
return $node;
}
Bash command redirections
There are 3 file descriptors, stdin, stdout and stderr (std=standard).
Available options:
- redirect stdout to a file
- redirect stderr to a file
- redirect stdout to a stderr
- redirect stderr to a stdout
- redirect stderr and stdout to a file
- redirect stderr and stdout to stdout
- redirect stderr and stdout to stderr
- 1 'represents' stdout and 2 stderr.
Note: with the less command you can view both stdout (which will remain on the buffer) and the stderr that will be printed on the screen, but erased as you try to 'browse' the buffer.
Sample: stdout to file
This will cause the ouput of a program to be written to a file.
ls -l > stdout.txt
Here, a file called 'stdout.txt' will be created and it will contain what you would see on the screen if you type the command 'ls -l' and execute it.
Sample: stderr 2 file
This will cause the stderr output of a program to be written to a file.
ls -l 2> stderr.txt
Here, a file called 'stderr.txt' will be created and it will contain what you would see the stderr portion of the output of the ' ls -l' command.
Sample: stdout 2 stderr
This will cause the stderr ouput of a program to be written to the same filedescriptor than stdout.
ls -l 1>&2
Here, the stdout portion of the command is sent to stderr, you may notice that in different ways.
Sample: stderr 2 stdout
This will cause the stderr ouput of a program to be written to the same filedescriptor than stdout.
ls -l 2>&1
Here, the stderr portion of the command is sent to stdout, if you pipe to less, you'll see that lines that normally 'dissappear' (as they are written to stderr) are being kept now (because they're on stdout).
Sample: stderr and stdout 2 file
This will place every output of a program to a file. This is suitable sometimes for cron entries, if you want a command to pass in absolute silence.
ls -l &> /dev/null
This (thinking on the cron entry) will delete every file called 'core' in any directory. Notice that you should be pretty sure of what a command is doing if you are going to wipe it's output.
Running background jobs in Unix
When you execute a Unix job in the background ( using '&', 'bg' command), and logout from the session, your process will get killed.
You can avoid this by executing the job with 'nohup' (stands for no hang up).
Usage:
nohup {command-with-options} &
'nohup' is very helpful when you have to execute a shell-script or command that take a long time to finish. In that case, you don’t want to be connected to the shell and waiting for the command to complete. Instead, execute it with nohup, exit the shell and continue with your other work.
Explanation about nohup.out file:
By default, the standard output will be redirected to nohup.out file in the current directory. And the standard error will be redirected to stdout, thus it will also go to nohup.out. So, your nohup.out will contain both standard output and error messages from the script that you’ve executed using nohup command.
You can avoid this by executing the job with 'nohup' (stands for no hang up).
Usage:
nohup {command-with-options} &
'nohup' is very helpful when you have to execute a shell-script or command that take a long time to finish. In that case, you don’t want to be connected to the shell and waiting for the command to complete. Instead, execute it with nohup, exit the shell and continue with your other work.
Explanation about nohup.out file:
By default, the standard output will be redirected to nohup.out file in the current directory. And the standard error will be redirected to stdout, thus it will also go to nohup.out. So, your nohup.out will contain both standard output and error messages from the script that you’ve executed using nohup command.
Difference between .bash_profile & .bashrc
WHEN working with Linux, Unix, and Mac OS X, I always forget which bash config file to edit when I want to set my PATH and other environmental variables for my shell. Should you edit .bash_profile or .bashrc in your home directory?
You can put configurations in either file, and you can create either if it doesn’t exist. But why two different files? What is the difference?
According to the bash man page, .bash_profile is executed for login shells, while .bashrc is executed for interactive non-login shells.
What is a login or non-login shell?
When you login (type username and password) via console, either sitting at the machine, or remotely via ssh: .bash_profile is executed to configure your shell before the initial command prompt.
But, if you’ve already logged into your machine and open a new terminal window (xterm) inside Gnome or KDE, then .bashrc is executed before the window command prompt. .bashrc is also run when you start a new bash instance by typing /bin/bash in a terminal.
Why two different files?
Say, you’d like to print some lengthy diagnostic information about your machine each time you login (load average, memory usage, current users, etc). You only want to see it on login, so you only want to place this in your .bash_profile. If you put it in your .bashrc, you’d see it every time you open a new terminal window.
Mac OS X — an exception
An exception to the terminal window guidelines is Mac OS X’s Terminal.app, which runs a login shell by default for each new terminal window, calling .bash_profile instead of .bashrc. Other GUI terminal emulators may do the same, but most tend not to.
My Recommendation
Most of the time you don’t want to maintain two separate config files for login and non-login shells — when you set a PATH, you want it to apply to both. You can fix this by sourcing .bashrc from your .bash_profile file, then putting PATH and common settings in .bashrc.
To do this, add the following lines to .bash_profile:
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
Now when you login to your machine from a console .bashrc will be called.
You can put configurations in either file, and you can create either if it doesn’t exist. But why two different files? What is the difference?
According to the bash man page, .bash_profile is executed for login shells, while .bashrc is executed for interactive non-login shells.
What is a login or non-login shell?
When you login (type username and password) via console, either sitting at the machine, or remotely via ssh: .bash_profile is executed to configure your shell before the initial command prompt.
But, if you’ve already logged into your machine and open a new terminal window (xterm) inside Gnome or KDE, then .bashrc is executed before the window command prompt. .bashrc is also run when you start a new bash instance by typing /bin/bash in a terminal.
Why two different files?
Say, you’d like to print some lengthy diagnostic information about your machine each time you login (load average, memory usage, current users, etc). You only want to see it on login, so you only want to place this in your .bash_profile. If you put it in your .bashrc, you’d see it every time you open a new terminal window.
Mac OS X — an exception
An exception to the terminal window guidelines is Mac OS X’s Terminal.app, which runs a login shell by default for each new terminal window, calling .bash_profile instead of .bashrc. Other GUI terminal emulators may do the same, but most tend not to.
My Recommendation
Most of the time you don’t want to maintain two separate config files for login and non-login shells — when you set a PATH, you want it to apply to both. You can fix this by sourcing .bashrc from your .bash_profile file, then putting PATH and common settings in .bashrc.
To do this, add the following lines to .bash_profile:
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
Now when you login to your machine from a console .bashrc will be called.
[PHP] Send attachment in mail
date_default_timezone_set('America/Los_Angeles');
// Create a file with data to send
$file_name = "summary.txt";
$myfile = fopen($file_name, "w") or die("Unable to open file!");
$txt = "PHP Mail function example with attachment" . PHP_EOL;
fwrite($myfile, $txt);
fclose($myfile);
$filetype = filetype($file_name);
//read from the uploaded file & base64_encode content for the mail
$content = file_get_contents($file_name);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("php-mail");
$from_email = 'from_email@gmail.com'; //sender email
$recipient_email = 'recipient_email@gmail.com'; //recipient email
$subject = 'Test mail'; //subject of email
$message = 'This is body of the message'; //message body
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$from_email."\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message));
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $filetype; name=\"$file_name\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
$sentMail = mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
die('Thank you for your email');
} else {
die('Could not send mail! Please check your PHP mail configuration.');
}
[PHP] Convert command line parameters to array
When we write a script which will be run from command line, we may have a need to pass in certain input params. This is similar to the GET/POST parameters that a web page uses as input params.
The function below is an easy way to convert the command line input params and use it like an array in the script.
// Convert arguments to key/value pairs, like the $_GET or $_POST arrays
$args = array();
foreach ($argv as $arg) {
if ($pos = strpos($arg, '=')) {
$key = substr($arg, 0, $pos);
$value = substr($arg, $pos+1);
$args[$key] = $value;
}
}
Input:
php run_my_script.php key1=value1 key2=value2 key3=value3
Output:
$args = [
'key1' => value1,
'key2' => value2,
'key3' => value3,
];
The function below is an easy way to convert the command line input params and use it like an array in the script.
// Convert arguments to key/value pairs, like the $_GET or $_POST arrays
$args = array();
foreach ($argv as $arg) {
if ($pos = strpos($arg, '=')) {
$key = substr($arg, 0, $pos);
$value = substr($arg, $pos+1);
$args[$key] = $value;
}
}
Input:
php run_my_script.php key1=value1 key2=value2 key3=value3
Output:
$args = [
'key1' => value1,
'key2' => value2,
'key3' => value3,
];
[PHP] Implement Stacks (LIFO)
class ReadingList
{
protected $stack;
protected $limit;
public function __construct($limit = 10) {
// initialize the stack
$this->stack = array();
// stack can only contain this many items
$this->limit = $limit;
}
public function push($item) {
// trap for stack overflow
if (count($this->stack) < $this->limit) {
// prepend item to the start of the array
array_unshift($this->stack, $item);
} else {
throw new RunTimeException('Stack is full!');
}
}
public function pop() {
if ($this->isEmpty()) {
// trap for stack underflow
throw new RunTimeException('Stack is empty!');
} else {
// pop item from the start of the array
return array_shift($this->stack);
}
}
public function top() {
return current($this->stack);
}
public function isEmpty() {
return empty($this->stack);
}
}
Output:
$myBooks = new ReadingList();
// add some items to the stack
$myBooks->push('A Dream of Spring');
$myBooks->push('The Winds of Winter');
$myBooks->push('A Dance with Dragons');
$myBooks->push('A Feast for Crows');
$myBooks->push('A Storm of Swords');
$myBooks->push('A Clash of Kings');
$myBooks->push('A Game of Thrones');
// remove some items from the stack
echo $myBooks->pop(); // outputs 'A Game of Thrones'
echo $myBooks->pop(); // outputs 'A Clash of Kings'
echo $myBooks->pop(); // outputs 'A Storm of Swords'
// top of the stack
echo $myBooks->top(); // outputs 'A Feast for Crows'
[PHP] Implement Linked List
/**
* Class Node
*/
class Node
{
public $data;
public $next;
public function __construct($item)
{
$this->data = $item;
$this->next = null;
}
}
/**
* Class LinkList
*/
class LinkList
{
public $head = null;
private static $count = 0;
/**
* @return int
*/
public function GetCount()
{
return self::$count;
}
/**
* @param mixed $item
*/
public function InsertAtFist($item) {
if ($this->head == null) {
$this->head = new Node($item);
} else {
$temp = new Node($item);
$temp->next = $this->head;
$this->head = $temp;
}
self::$count++;
}
/**
* @param mixed $item
*/
public function InsertAtLast($item) {
if ($this->head == null) {
$this->head = new Node($item);
} else {
/** @var Node $current */
$current = $this->head;
while ($current->next != null)
{
$current = $current->next;
}
$current->next = new Node($item);
}
self::$count++;
}
/**
* Delete the node which value matched with provided key
* @param $key
*/
public function Delete($key)
{
/** @var Node $current */
$current = $previous = $this->head;
while($current->data != $key) {
$previous = $current;
$current = $current->next;
}
// For the first node
if ($current == $previous) {
$this->head = $current->next;
}
$previous->next = $current->next;
self::$count--;
}
/**
* Print the link list as string like 1->3-> ...
*/
public function PrintAsList()
{
$items = [];
/** @var Node $current */
$current = $this->head;
while($current != null) {
array_push($items, $current->data);
$current = $current->next;
}
$str = '';
foreach($items as $item)
{
$str .= $item . '->';
}
echo $str;
echo PHP_EOL;
}
}
$ll = new LinkList();
$ll->InsertAtLast('KP');
$ll->InsertAtLast(45);
$ll->InsertAtFist(11);
$ll->InsertAtLast('FE');
$ll->InsertAtFist('LE');
$ll->InsertAtFist(100);
$ll->InsertAtFist(199);
$ll->InsertAtLast(500);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(45);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(500);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
$ll->Delete(100);
$ll->PrintAsList();
echo 'Total elements ' . $ll->GetCount();
echo PHP_EOL;
Output:
$ php LinkList.php
199->100->LE->11->KP->45->FE->500->
Total elements 8
199->100->LE->11->KP->FE->500->
Total elements 7
199->100->LE->11->KP->FE->
Total elements 6
199->LE->11->KP->FE->
Total elements 5
Sunday, August 18, 2013
'this'
var foo = {
first: function(){
console.log('I am first');
},
second: function(){
console.log('I am second');
},
};
foo.first();
foo.second();
Everything works fine.
Now there is a need for function second to call function first. Try this and it will fail.
var foo = {
first: function(){
console.log('I am first');
},
second: function(){
console.log('I am second');
first();
},
};
foo.second();
One way to fix this problem is to hardcode value foo inside the second function. Following code works.
var foo = {
first: function(){
console.log('I am first');
},
second: function(){
console.log('I am second');
foo.first();
},
};
foo.second();
Above code works but hardcoding the value of foo inside the object literal is not good. A better way would be to replace the hardcoded name with this .
var foo = {
first: function(){
console.log('I am first');
},
second: function(){
console.log('I am second');
this.first();
},
};
foo.second();
All is good.
Chasing this
Javascript allows one to create function inside a function. Now I am changing the implementation of method second. Now this method would return another function.
var foo = {
first: function(){
console.log('I am first');
},
second: function(){
return function(){
this.first();
}
},
};
foo.second()();
var foo = {
first: function(){
console.log('I am first');
},
second: function(){
return function(){
this.first();
}
},
};
foo.second()();
var foo = {
first: function(){
console.log('I am first');
},
second: function(){
var self = this;
return function(){
self.first();
}
},
};
foo.second()();
Sunday, June 9, 2013
Truth Table / Power Set
Output:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
printTruthTable("", 0, 3);
$originalArr = array('a', 'b', 'c');
$outputArr = array();
powerSet("", 0, 3);
var_dump($outputArr);
function printTruthTable($str, $start, $strLength) {
if ($start === $strLength) {
if (/*Truth Table*/) {
var_dump($str);
}
if (/*Power Set*/) {
global $originalArr;
global $outputArr;
$tempArr = array();
for($i=0; $i<$strLength; $i++){
if ($str[$i] === 1) {
array_push($tempArr, $originalArr[$i]);
}
}
array_push($outputArr, $tempArr);
}
return;
}
$str[$start] = 0;
printTruthTable($str, $start+1, $strLength);
$str[$start] = 1;
printTruthTable($str, $start+1, $strLength);
}
OR
function printPowerSet($set, $set_size)
{
/*set_size of power set of a set with set_size
n is (2**n -1)*/
$pow_set_size = pow(2, $set_size);
for($counter = 0; $counter < $pow_set_size; $counter++)
{
for($j = 0; $j < $set_size; $j++)
{
if($counter & (1 << $j))
echo $set[$j]; // echo
}
echo PHP_EOL;
}
}
$set = 'abc';
printPowerSet($set, 3);
Thursday, December 13, 2012
[JS] Function Bind
Why you need this?
var x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
// ----------------------------------------------------
var x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
// ----------------------------------------------------
Function.prototype.bind = function(oThis) {
var args = Array.prototype.slice.call(arguments, 1);
var fToBind = this;
var fToReturn = function() {
return fToBind.apply(oThis, args.concat(Array.prototype.slice.call(arguments)))
}
return fToReturn;
}
[JS] Function Currying
Currying allows you to easily create custom functions by partially invoking an existing function. Here’s a simple example:
var add = function(a,b) {
return a + b;
}
//create function that returns 10 + argument
var addTen = add.curry(10);
addTen(20); //30
// ----------------------------------------
Function.prototype.curry = function() {
if (arguments.length<1) {
return this; //nothing to curry with - return function
}
var fToBind = this;
var args = Array.prototype.slice.call(arguments); // Converting to array
return function() {
return fToBind.apply(this, args.concat(toArray(arguments)));
}
}
var add = function(a,b) {
return a + b;
}
//create function that returns 10 + argument
var addTen = add.curry(10);
addTen(20); //30
// ----------------------------------------
Function.prototype.curry = function() {
if (arguments.length<1) {
return this; //nothing to curry with - return function
}
var fToBind = this;
var args = Array.prototype.slice.call(arguments); // Converting to array
return function() {
return fToBind.apply(this, args.concat(toArray(arguments)));
}
}
Tuesday, October 16, 2012
Palindrome
$a_inputString = "raddar"
function isPalindrome($a_inputString)
{
$frontPointer = 0;
$backPointer = str_length(inputString)-1;
while ($frontPointer < $backPointer)
{
if ( strcmp(substr($inputString, $frontPointer, 1)
(substr($inputString, $backPointer, 1) == false)
return false;
$frontPointer ++;
$backPointer --;
}
return true;
}
Merge sorted lists
Question:
n lists, each is sorted, each has size m
merge into one sorted list, overall size n*m
Easy Solution:
1. Pointers pointing to each position of the array
2. Compare the element at the positions
3. Find the minimum and insert in the outputArray
Complexity
1. Traverse all the lists (n*m)
2. Comparisons to find the minimum element ((n-1) comparisons)
O((n*m)(n-1)) = O(n^2*m)
1. n-size heap
2. log n to insert in heap
3. O(n*m*logn)
n lists, each is sorted, each has size m
merge into one sorted list, overall size n*m
Easy Solution:
1. Pointers pointing to each position of the array
2. Compare the element at the positions
3. Find the minimum and insert in the outputArray
Complexity
1. Traverse all the lists (n*m)
2. Comparisons to find the minimum element ((n-1) comparisons)
O((n*m)(n-1)) = O(n^2*m)
MinHeap heap = new MinHeap();
// $inList[n] - Input Lists
$outputArr = array();
// Push first elements of all the lists in the MinHeap
for (int i=0; i<n; i++)
{
heap.push(i, array_pop($inList[i]));
}
/*
1. Pop element from MinHeap
2. Push the next element from the inList from which the element was pop'd
3. Do this till the MinHeap is empty
*/
$popObj = heap.pop();
while (!empty($popObj))
{
$listId = $popObj["listId"];
$elementPop = $popObj["leastElement"];
$outputArr[] = $elementPop;
heap.push($listId, array_pop($inList[$listId]));
}
// Complexity1. n-size heap
2. log n to insert in heap
3. O(n*m*logn)
Friday, October 12, 2012
Friday, September 28, 2012
Using XOR operator for finding duplicate element
A XOR statement has the property that 'a' XOR 'a' will always be 0, that is they cancel out, thus, if you know that your list has only one duplicate and that the range is say x to y, 601 to 607 in your case, it is feasible to keep the xor of all elements from x to y in a variable, and then xor this variable with all the elements you have in your array. Since there will be only one element which will be duplicated it will not be cancelled out due to xor operation and that will be your answer.
void main()
{
int a[8]={601,602,603,604,605,605,606,607};
int k,i,j=601;
for(i=602;i<=607;i++)
{
j=j^i;
}
for(k=0; k<8; k++)
{
j = j^a[k];
}
// j = duplicate element
}
Variation:
An array of 2 elements - one element occurs even number of times & the other odd number of times. How would you find the value that occurs odd number of times ?
Get all the unique numbers in the array using a set in O(N) time. Then we XOR the original array and the unique numbers all together. Result of XOR is the even occurring element. Because every odd occurring element in the array will be XORed with itself odd number of times, therefore producing a 0. And the only even occurring element will be XORed with itself even number of times, which is the number itself.
Reason:
XOR a number with itself odd number of times we get 0,.
XOR a number with itself even number of times then we get the number itself.
Get all the unique numbers in the array using a set in O(N) time. Then we XOR the original array and the unique numbers all together. Result of XOR is the even occurring element. Because every odd occurring element in the array will be XORed with itself odd number of times, therefore producing a 0. And the only even occurring element will be XORed with itself even number of times, which is the number itself.
Reason:
XOR a number with itself odd number of times we get 0,.
XOR a number with itself even number of times then we get the number itself.
You are given an array of integers and a sum. Find all pairs of integers that equal that sum. Assume you have some sort of data structures that will be able to store the pairs. Write an algorithm to find all these pairs
Solution1
O(n^2) solution - Have two for loops
Solution2
Using a hashMap
Solution3
Most efficient - as no extra storage like hashMap
Sort the array
Two pointer - one to the begining and the other to the end of the array.
Compare the values pointed by the pointers untill the pointers collide
If the sum is lesser than m then increment the left pointer by one
If the sum is greater than m then decrement the right pointer by one
If the sum is equal to m then return "YES"
Wednesday, August 29, 2012
Swap without using 3rd variable
Swap Algorithm
A = A + B
B = A - B
A = A - B
You can not use this approach as while adding A & B (A + B), it could result in a "OVERFLOW"
Hence, we use this approach
X := X XOR Y
Y := X XOR Y
X := X XOR Y
A = A + B
B = A - B
A = A - B
You can not use this approach as while adding A & B (A + B), it could result in a "OVERFLOW"
Hence, we use this approach
X := X XOR Y
Y := X XOR Y
X := X XOR Y
Subscribe to:
Posts (Atom)