Monday, June 29, 2015

808: Reverse Integer / Integer Palindrome

The popularity of my Find the middle of linked list in one pass post here is another classic interview question.  Once again the goal of this question is to see if you strip away the libraries and tools from the software engineer does she still have to fundamentals needed to think through a problem.

Determine if a given integer is a palindrome. 

(think about it before you jump to see what the answer is)










Once you complete your solution on the whiteboard ask a question or two. Such as can negative numbers be consider palindromes? Can numbers that end in zero be palindromes? (example: does 100 == 00100) Asking a question shows your understanding of the problem and the ways algorithm can be enhanced.

Java Solution:

boolean isPalindrome(int x) {
 return x == reverse(x);

int reverse(int x) {
 int result = 0;
 int digit = x;
 while (digit > 0) {
  int modulus = digit % 10;
  digit = digit / 10;
  result = result * 10 + modulus;
 return result;

Related Content:

Wednesday, June 24, 2015

Find middle of a Linked List in one pass/loop (Pseudo code/Java/JavaScript)

This is a classic interview question that I think most engineers should basically have memorized.  Why; because it is a simple problem with a simple solution but very low level compared to our day to day activities.  Doing stuff like this regularly even as a senior engineer is important exercise for your mind.

I have been asked this question I half dozen times in job interviews.  If at some point in time in the future I am ever interviewing you, watch out of this question because I like to use it as an opener. (If you read my log and I am interviewing you then I think you should have a leg up on the competition.)

Write an algorithm to find the middle node of the linked list. With the caveat that you can only make a single pass through the list.

(think about it before you jump to see what the answer is)










Disclaimer: Some people feel this is 1.5 list traversals despite using a single loop.  This question and solution is not unique to this blog post so opinions of this are mixed. I respect that and you should form our only opinion,

The solution is straightforward once you step back and think slowly.  Have two pointers that traverse the list but one of them only moves every other time.  So by the time the faster moving pointer gets through the list your second pointer is at the middle node.

The problem I ran into was... basic linked list really aren't a part of normal libraries.  I have never attempted taking this algorithm beyond pseudo code before so it was a fun little challenge to implement as simply as possible.

Pseudo code

    Node current = LinkedListHead;
    int length = 0;
    Node middle = LinkedListHead;
    while( != null){
        if(length % 2 == 0) {
            middle =;
        current =;

    return middle;

Java Solution

public class MiddleOfList {
    public String findMiddleOfList() {
        LinkedListNode tail = new LinkedListNode("data5", null);
        LinkedListNode node4 = new LinkedListNode("data4", tail);
        LinkedListNode node3 = new LinkedListNode("data3", node4);
        LinkedListNode node2 = new LinkedListNode("data2", node3);
        LinkedListNode head = new LinkedListNode("data1", node2);
        return findMiddle(head);
    private String findMiddle(LinkedListNode head) {
        LinkedListNode current = head;
        int length = 0;
        LinkedListNode middle = head;
        while(current.nextNode != null){
            if(length % 2 == 0) {
                middle = middle.nextNode;
            current = current.nextNode;
    private class LinkedListNode {
        public String data = null;
        public LinkedListNode nextNode = null;
        public LinkedListNode(String data, LinkedListNode nextNode) {
   = data;
            this.nextNode = nextNode;

JavaScript Solution

Here is an implementation on JsFiddle.  This is an attempt to keep things as simple as possible.

var tail = {data: "data5",next: null};
var node4 = {data: "data4",next: tail};
var node3 = {data: "data3",next: node4};
var node2 = {data: "data2",next: node3};
var head = {data: "data1",next: node2};

var current = head;
var length = 0;
var middle = head;

while ( != null) {
    if (length % 2 == 0) {
        middle =;
    current =;

Other programming challenges: 

Thursday, June 18, 2015

Can your tests survive the coming mutant apocalypse? [REPOST]

Are your unit tests effective against code mutations? No, you don't need to worry about your code being bombarded by gamma rays or being bitten by a radioactive spider. The question is will your tests catch minuscule changes in the code base that could have disastrous affects. Mutation testing has been around since 1971 but the majority of people in the software world haven't heard of it. So congratulations you have just learned something that can wow and amaze your peers at the lunch table.

Breaking code is easy

This may be earth shattering news but software engineers are not perfect. We make mistakes but that is why we test. The code written during a 2am coding bender all hyped up on Jolt Cola may be the stuff of legend that creates the next paradigm shifting application but one typo can result in catastrophe. Have you ever spent hours upon hours debugging a critical defect that resulted in something silly like the usage of the wrong operator or worse a missing semicolon?

100% code coverage != effective tests

Despite our best intentions test code is not treated with the same respect as the rest of your code base.  One hundred percent code coverage is a unicorn, really really rare, in complex applications but even that is not enough to ensure your code is rock solid. Even if your unit tests result in a perfect code coverage report, are you positive all your assert statements are effectively verifying the results? Mutant testing is essentially tests for your tests.

And you know what the worst part is? 

If you are taking the time to read this then there is likely no need to convince you of how vital testing is. However, effective test writing is a skill/art/science but it is one of the many critical skills in the software engineering world that they likely did not teach you in college. Formal training on unit test writing is virtually unheard of. During code reviews the test code is not given the same type of scrutiny as the production code. Yet the tests are just as critical to the long term success of your project.

So what is mutation testing?

Your tests ensure your application works as you expect it to but what ensures that your tests sufficiently protect your application. Mutation testing is effectively making minor changes to your source code and ensuring your tests catch it and none of those mutants survive. A mutant that survive could one day grow up to be a defect.
mutant survival score = number of mutants killed / total number of mutants

The creation of a mutant army

As previously discussed mutants are brought into existence by sightly modifying your source code with something as simple as changing an equals into a not equals. Doing this for every conditional, arithmetic, relational, and assignment operator is just the beginning but you can see how the number of mutations even for a fairly simple piece of code can grow quickly.

    public int additionOrSubtraction(boolean isAddition, int x, int y) {
        if (isAddition) { //mutant: replace isAddition with !isAddition
            return x + y; //mutants: replace + with -,*,/,%
        } else {
            return x - y; //mutants: replace - with +,*,/,%

The code above could result in 50 or more mutants which your unit tests would then be executed against.  If any of those mutants do not cause a test failure it "survives."

Creating a mutant army is not something you want to be doing by hand so look for tools available in your language of choice. Mutation testing is done almost exclusively with unit tests in mind. That is not to say that throwing a few mutants randomly against your integration tests would not be valuable too but throwing a fully mutant army against your functional tests would be absurdly costly.

Are you scared of the mutants yet?

Do not alarmed. These mutants are here to save you. Send in the mutants! Save your tests. Your project could be one fat fingered key stroke away from disaster.

Find out more: Give your tests mutant powers with PIT [Part 1]

Post with my own permission as the original author.  (Source)

Wednesday, June 17, 2015

Start your own blog today!

I am a big fan of blogging.  Personally I find that it helps me organize my thoughts and gain a deeper understanding of topics. Blogging can also be great for your career as well.  When recruiters contact me they often reference my blog and something they read on it. One day it could lead to a job referral or a promotion from one of my followers.

You account for maybe 0.5-1% of my average daily usage of my humble blog.  Think about that. Blogging does not have to be of benefit to you 100% of the time. If even 1 out of 1,000 visitors thinks you could be a great addition to their team or thinks they would like to work with you then your career prospects could skyrocket.  Blogging opens doors. Nothing beats an in house referral.

John Sonmez (Simple Programmer), who you may have heard me metion a few times, has a free blog course available.  The course is done via email which is perfect for learning at your own pace and not fall off the bandwagon a couple days after you decide to start blogging.
There are lots of information about why you should blog. I have not interested in adding to the noise, but here is why I am blogging.  Maybe you well see something that tips you over the edge to make the commitment to sign of for the course.

Professional Growth
  • Blogging improves your writing skill.
  • It improves your ability to explain potentially complex concepts.
  • It helps me learn because I try to "teach" some of the new technologies I encounter as a way of organizing my thoughts.
Career Growth

  • networking - It is not news that the more people you know the more opportunities are available to you.  This isn't just for job searching but your current team needs the best possible talent too and networking helps find that talent.  Hiring someone from within your network is much less of a gamble.
  • marketing / branding - This does not have be something dirty to shy away from.  Branding yourself is just a way to consistently express who you are and how you add value. 
  • visibility - Some of the best engineers I have met over the course of my career have also been the most introverted. Blogging is a good way to get people out of there shell without a need to leave your desk. Not only that but you can reach a huge audience vs just the people standing by the water cooler.
  • resume supplement - Even if someone doesn't recognize you by name they can easily go to your blog and get a taste of who you are.  Job interviews often go quick.  In phone screens you get 10 to 15 minutes to express how you are worth bringing in for a face to face bit with a blog you can extend that engagement.  Your potential employer may even know you are worth bringing in for a face to face interview just because they cam see your value via your blog.
Good for your company
WHAT?!? How can blogging be good for the company you work for? Blogging helps get your name out there, right? In all the ways that blogging is good for your personal career growth it is good for your company because you are becoming a better employee.  Not only that since your name is in someway linked to them it reflect positively on them. The people you mentor, network with, or even just see your LinkedIn profile now see your company linked to it. When you are looking for a new position wouldn't you want to go somewhere you know other talented engineers work? Talent attracts talent. Corporate blogs are almost always boring but a personal blog from an employee of the company can give you a nice glimpse at the culture and people in the organization.
Giving Back
The internet has helped me solve countless problems professional and personally but what have I done to contribute back?  Stack Overflow for example helped me out of many sticky situations but up until recently I never answered one question there.  I never even asked my own question.  I was just a Stack Overflow voyeur. Starting this blog is in part a way to help me give back to the community.  If I am working through a problem chances are someone else will be in a similar spot in the future so why not write it down.

I don't know by this point if you are convinced or not if you should start your own blog or not. If you are ready to start blogging go sign up for John's course and if you are not go read more about blogging on John's site and maybe he can convince you.  If you are still not convinced read John's book and get on the soft skills bandwagon.  Seriously, there is too much to gain and nothing to lose.

My blogging mentor: Daniele Rossi

Thursday, June 11, 2015

Give your tests mutant powers with PIT [Part 2]

Mutation testing series:

PIT has the ability to run mutation test with ant, maven, gradle, and more so it can easily be run via the command line and in your favorite build environment. The cost of entry into the mutation testing world is low for Java with PIT.  

Sample Project:

I created a little sample project to try mutation out which are welcome to clone. It is nothing special but I wanted to play with it somewhere other than on an enterprise application. Mutation testing can take while to run on large projects so I would recommend experimenting with the concepts on a smaller scale.
Sample Project on Git Hub

How to add PIT to a Maven project:

Step 1: Update that pom to include the following: (replacing the project base package of course)


Step 2: Pat yourself on the back because your project is not setup for mutation testing.

How to run PIT mutation tests:

Running mutations tests are super simple from the command line.

> mvn org.pitest:pitest-maven:mutationCoverage

* One thing to note is the command above line assumes it is already compiled locally.

Depending on your project size this can take a while to run. PIT does display a ascii spinner so you know the mutation (slave) haven't stalled so you remain patient. In the sample project I was explicit about where the mutation report should go by but by default they are saved in target/pit-reports/YYYYMMDDHHMI.

There are a lot of command line options but you can see them on the PIT website. One of the more interesting ones to me was the "mutators" option where you can specify which mutators to run against your code.  There are some which are not used by default like "remove conditionals mutator" (REMOVE_CONDITIONALS).

> mvn org.pitest:pitest-maven:mutationCoverage -Dmutators=REMOVE_CONDITIONALS,MATH

Although the most useful initially may be the "mutationUnitSize" option.  It will help to ensure your mutant army doesn't grow too large by specifying the maximum number of mutations created per analysis.

> mvn org.pitest:pitest-maven:mutationCoverage -DmutationUnitSize=2

My experience on a real project:

The small, but real enterprise project I started using this on had about 800 unit tests and ended up generating around 2,500 mutations. The test build which normally takes about 30 seconds now took almost 9 minutes with mutation testing. So cost of doing mutation testing is nothing to sneeze at but it is worth it. I would not recommend mutation testing to be done as part of a continuous integration but rather as part of a nightly build to generate the reports. The project used for this initial test has 98% line and 100% conditional coverage.  (Yes, as previously admitted I am a bit obsessive about unit testing,)  However much to my embarrassment the mutation coverage was only 88% .

The mutation testing results showed the value of mutation testing so clearly. Silly stuff was missed like a mutant survived where a line of code which added an element to a list was removed. (How could we have missed an assert to verify an element was not added to the list!) Also there were mutants that survived where lines where properties were set were removed and negated conditional mutants also survived.  It is the simple stuff, the seemingly trivial stuff, that gets overlooked until you spend hours debugging a defect which ends with you banging your head on your desk saying how could I have missed that.

The project does unit test at a class level with mock objects powered by Mockito. The thing that could have helped kill these mutations more than anything else was Mockito.verifyNoMoreInteractions(someMock, anotherMock). It is best practice to have it in there but it often is forgotten about once you finish verifying the results.

Tuesday, June 9, 2015

Give your tests mutant powers with PIT [Part 1]

Mutation Testing basics:  Can your tests survive the coming mutant apocalypse? (LinkedIn)

Mutation testing opens exciting possibilities. Let's start doing it.  Now, stop waiting and just do it.

PIT seems to be regarded as the tool of choice in the Java software development world.  PIT has a maven plugin which can help make it a part of your daily builds.  The tool also works with ant, gradle, and more.  There is even a Sonar plugin available to integrate the mutation testing reports will all your other coverage reports. After you read this post go to the PIT website ( and check out all it has to offer.

The cost of entry with the Maven plugin is low but it is not low enough for me,  There is configuration needed to get your project up and running with PIT and the documentation leaves a little be desired. However there is almost no cost to you to install the PIT Eclipse plugin. The plugin that lets you do all the same mutation magic but in eclipse without needing to update your projects pom file and saves you the trouble from running on the command-line. It allows you to limit the tests that are used for mutations very easily.  You can get this going in less than 10 minutes in the morning and be prepared to show it to people at the lunch table.

There are disadvantages to mutation test.  For example it is time consuming and resource intensive.  Which is all the more reason why you should ease into it and put your toes in the water with the eclipse plugin.  It will help you quickly see the value of it.

The plugin can be added via the eclipse market place by searching for the name "PitClipse".  If you need more information about it check out the marketplace website:

The results can be seen in a tree structure in eclipse vs using the html report generated via the command line.

The html report can also been seen in eclipse but I personally feel the tree view is more usable.

Don't wait! Install the plugin and get started.  Once you see the mutations that survive from the unit tests you have told yourself are good enough you will be convinced that mutation testing is the way to go.

Give your tests mutant powers with PIT [Part 2]

Wednesday, June 3, 2015

Mentoring via Stackoverflow

It was a slow evening for me so I created a stackoverflow account and started answering questions. For years I have found great answers on the site but never contributed back.  However in the process of looking at the questions coming in I realized this is actually very similar to mentoring junior engineers.  I don't get too many opportunities to mentor because these I end on working in top heavy teams.  As I was answer questions I got a very similar feeling as mentoring.  It seems to me like a good way improve your mentoring communication skills and give back to a community which I am sure we all have used.

Here is my profile on stackoverflow if care to cyberstalk me:

profile for Bobby at Stack Overflow, Q&A for professional and enthusiast programmers

Tuesday, June 2, 2015

AngularJS - a journey towards specalization

In a previous post I spoke about a desire to specialize.  For right now I think I am going to work on being a AngularJS front end and Java Spring middle tier guy.  I have been working with Java for a decade so no problem there.  Also being a full stack generalist for years I have done plenty of front end work but never really mastered the craft.  With a new job I am starting in a couple weeks I will have the chance to put my academic knowledge of AngularJS to use and start building a practical knowledge base.  Who knows if I will want to specialize in this in a year but for now this is a good place to start.

Following a recommendation by John Sonmez, the Simple Programmer, I should not only try to specialize in my skill set but also this blog.   So I will try to focus this blog now on three topics
  • AngularJS - writing about my journey from beginner to master
  • Java - general software development and algorithms
  • Unit Testing - this is my true passion in software development that I can never really escape