100 ways to skin an interview question

February 24, 2010

In a recent interview, I was asked the following question:

Write a program to determine the 10th Fibonacci number.

Without further specification, this problem is worthless. Depending on the scope and nature of the program, the solution to this problem will vary wildly. For example, will this function get called in a tight inner loop? What are the memory constraints? What are the concerns with respect to reusability? I’ll make this more concrete below.

Naive solution

def F(n):
   if n == 1 or n == 0:
      return 1
   return F(n-1) + F(n-2)

Why this is completely wrong: What happens when you pass a fractional value to F(n)? You break. What happens if you pass a negative value? You break. You could fix this by checking if n <= 1 in the base case, but then you still have unneeded redundancy. Without explicitly defining the interface by which you generate a series, you've broken your code completely. Expect bugs, and expect huge memory waste. These results could be memoized, but consider the initial problem statement. Was there any implication that anything other than F(10) would need to be computed? No. This gives us a rather smart-ass solution.

Efficient Solution

Consider the following:

#define Fib10 89

If you can’t trust the compiler, memory constraints are tight, or performance is an issue, precomputation is clearly the solution. You KNOW F(10) without any programming whatsoever. You can compute it by hand and yield the above result. A more scrupulous reader might notice that F(10)==89 isn’t easily verifiable without writing code. A better solution might look like this.

Verifiable Efficient Solution

#define Fib10 (1+1+2+3+5+8+13+21+34+55)

It’s still sloppy, but it’s as efficient as the previous solution and easier to verify. This solution, however, has a fatal flaw: it only works for one value of N (although you could define more), and it’s not reusable at all. A compromise between efficiency and reusability might give you the following.

The Compromise Solution

Fib = [1,1]
for i in range(2,100):
   Fib.append( Fib[i-1]+Fib[i-2] )

This has no edge cases, it’s rather easy to verify, and you can adjust the maximum required value as necessary. This requires a fixed max size, though, which means it’s sure to break at some point. At best, you’re stuck with documenting this limitation. Once again, we consider memoization, but we can remember to avoid the unnecessary recursion to keep the solution a bit more efficient.

So, then, what do you do? Create something reusable.

The Reusable Solution

The code is getting funkier, so I’ll leave this as an exercise to the reader for now. Essentially, we can encapsulate the compromise solution in a class. If a client requests a Fibonacci number greater than that which we’ve precomputed, we compute up to the given value and store the intermediate computations. This solution, however, ignores the fact that most would ignore when approaching this problem.

The Math Solution

Namely, Fibonacci numbers can be generated in constant time with Binet’s formula.

For reasonable values of N, the rounding formula provides exact values.

The Real Solution

So what, then, is the right answer? It really depends on information left out of the problem statement. In the real world, you would probably just use a math library to get the values, knowing that someone has gone through the same thought process through which you’ve just gone. If this isn’t possible, then you have to consider one of the above methods.

One might argue that this reasoning ability is what an interviewer should be looking for, but that was not the emphasis of the question. Really, there are just better questions you can ask a person to figure out if they’re worth their salt, unless, of course, you’re really just pre-screening, at which point you’re just looking for the response “89.”

Copying a file in Java

February 17, 2010

Code snippet. Why isn’t this part of the Java API?

Just use commons.

<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</groupId>
   <version>1.4</version>
</dependency>

FileUtils gives us this:

public static void copyFile(File srcFile, File destFile) throws IOException

Ruby and named regex matched groups.

February 17, 2010

Back from China, I’ve resume my normal programming schedule. I’m working through Pragmatic Bookshelf’s Programming Ruby, and there’s a lot more to ruby than I initially gave credit. For example, consider the following:

str = 'an' * 3000 + 'garbage' + 'an'*3000
r = /(?<pattern>.*) #The first part
    (?:.*?) #Garbage
    \k<pattern>/x #The first part, repeated.
str =~ r
puts $1.length

First, we create a repeated string, followed by some garbage data, followed by that string again. A pattern is built to find the largest prefix which is also a suffix, given a break in data. Ruby lets us name the regex

A break from (sexy) learning

January 21, 2010

For the past month, I’ve been unable to study anything new and sexy. Rather, I’ve been preparing for the ICPC 2010 World Finals.

Most recently, I’ve been working on this:

ICPC Challenge Screenshot

Essentially, contestants build an AI to battle it out in an FPS-esque arena. It was really quite interesting, although it required serious time input.

For more info, look here. My team really only had one good pre-submission, but our final product should be competitive.

If you’re interested in participating in AI battling tournaments, you might want to check out the newly created ACM Queue Challenge.

XSLT: How you should be transforming XML into HTML.

January 5, 2010

XSLT is a method of transforming XML with a set of rules, functions, and selectors. Transformations can be complex or simple, but the benefit of using XSLT is immediately obvious after first use.

Consider the following:

<posts>
   <post>
      <title>XSLT!</title>
      <description>A short post about XSLT</description>
      <content date = "01/03/2009">
      Lorum ipsum
      </content>
   </post>
<posts>

The naive approach of displaying this to the user is to manually parse the data with an XML parser of some kind. I’ve done this in previous projects; it works, but it’s generally stuck in code, which means that changes to the output format require recompilation or some other elaborate build and deployment. This is inherently wrong given the process that’s taking place. A transformation of XML can and should be independent from the XML itself.

Here’s some pseudocode for the rendering of an XML document into HTML:

html = '<html><body>'
for node in document.find( 'post' )
    title = node.find( 'title' ).text
    descriptionNode = node.find( 'description' )
    postDate = descriptionNode.attribute( 'date' )
    descriptionText = descriptionNode.text

    html += '<div>'
    html += '<h1>' + title + '</h1>'
    html += '<p>' + descriptionText + '</p>'
    html += '<p><em>' + postData + '</em></p>'
    html += '</div>'

html += '</body></html>'
render(html)

While this is straightforward enough in the trivial example, it falls apart when parsing large, complex documents. Consider now the XSLT equivalent:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:template match="/">
        <html>
            <body>
                <xsl:apply-templates />
            </body>
        </html>
    </xsl:template>
    <xsl:template match = "post">
        <div>
            <xsl:apply-templates />
        </div>
    </xsl:template>
    <xsl:template match = "title|description">
        <p><xsl:apply-templates /></p>
    </xsl:template>
    <xsl:template match = "content">
        <p><xsl:apply-templates /></p>
        <p><em><xsl:value-of select="@date" /></em></p>
    </xsl:template>
</xsl:stylesheet>

Although the trivial example is longer in terms of characters, there are numerous benefits to this approach.

  1. The transformation is externalized. If you decide that all post divs now need a “post” class, you don’t need to recompile, and you know exactly where to make the change.
  2. Presumably, your XSLT editor can validate XML, or at least tell you when you’re missing a closing angle bracket or two. Most IDEs will not see unclosed angle brackets within strings as a problem, so in you get a proper environment in which to craft your output HTML. Sure, you could use an XML library that hides this implementation from you, but you still run the risk of missing an element or forgetting to append nodes to one another. This wastes time. With a XSLT document, you can very clearly easily about your output before testing. This emphasizes another issue.
  3. Good XSLT editors will let you quickly and easily run XSLT against XML. Using oXygen, I was able to develop the above document in under a minute. Actually testing manually-manipulated XML, on the other hand, takes much more time.

All of this said, there are still reasons to avoid XSLT in certain situations. All browsers do not support XSLT, and there are few XSLT 2.0 processors at the moment. Ergo, you must perform your transformations on the server, rather than on the client, but you should probably be doing that anyway. Furthermore, maintenance programmers will need to know XSLT to debug and extend your application, so if you’re worried about limited knowledge handling your software, it may be best to simply avoid XSLT altogether.

I’ve quickly found that XSLT is often the right tool for the job, however, so it would be a sin to not learn enough of the technology to recognize when its applicable and when it isn’t. Don’t craft your HTML by hand, but only use XSLT when it’s appropriate.

Why I chose Linode as a webhost

November 24, 2009

Linode.com offers linux virtual private server (VPS) systems that you can use to do anything. Now, when I say anything, I don’t mean we’ll-give-you-unlimited-databases anything, I mean ANYTHING anything. If you google search correctly, you can find reports of customers using their Linode to host Left4Dead servers, within the terms of use. So, then, here are my reasons for using Linode as a server solution.

Flexibility

As mentioned, Linode lets you do anything. Currently, I use my server to host subversion, tomcat, apache, MySQL, postfix email, and random files. But surely, you say, the hardware must be oversold, or you’re restricted in some crippling manner? Well, not really. I come nowhere close to my guaranteed bandwidth, CPU, or memory allotment with the smallest package available:

Linode 360:

  • 360MB RAM
  • 16GB Disk Storage
  • 200GB/mo transfer
  • $19.99/mo

The only perceivable downside to this flexibility…is the flexibility. When you create a server, you start with a flat, uninteresting linux distribution. You must manually install apache, tomcat, subversion, and whatever other services you wish to run. This configuration, however, lets you fine-tune the system to your exact specifications, and it lets you learn how to do all that in the process. With SSH at your side, you too can become a Linux ninja and master the lore of old. You’ll probably wind up a more efficient developer, and at the very least you’ll learn a neat Unix command or two.

Price

$19.99/mo for a web server seems pricey, but it really isn’t. You’re buying power, guaranteed reliability, and ownership of your server. By Linode’s own FAQ, hardware resources are guaranteed, and when the system is able, bursts of usage beyond are allowed. With a general web host, you’re stuck to whatever you’re given. The only other competition in this arena, really, is Slicehost. Their base $20/mo package only includes 256MB of RAM, however, which is simply unacceptable when a 384 solution exists for the same price.

Reliability

In the 5 months I’ve owned my Linode account, my server has only gone down once, for a 1-hour period. I was rather upset at the outage, as I use my server nightly, but I was not riled enough to seek a $0.66 refund. Performance, too, has always been top-notch. Not once have I ever noticed latency, which is simply incredible compared to general web hosts.

Conclusion

Linode is amazing, and if you believe me, click the referral link I hid in the first word of this post. If you stay on 3 months with my referral code, I get a month free.

Cheers. :)

Spring 2.5 with SpringMVC

November 19, 2009

This month, I decided to go more in-depth with Spring and SpringMVC and model the web services for a CMS/Shopping Cart system. With Spring, Tomcat, XOM, and JUnit, I was able to speedily throw together a modular, DI-driven web service that implemented a simple web service interface without needing to worry about database details or request mapping.

Specifically, Spring’s MultiActionController and XOM’s XML building utilities let me write the minimal AccountController given below.

public class AccountController extends MultiActionController
{
private AccountManagementService accountManagementService;

public ModelAndView login( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
   String username = StringEscapeUtils.escapeHtml( request.getParameter( "username" ) );
   String password = StringEscapeUtils.escapeHtml( request.getParameter( "password" ) );
   Document xmlDoc = accountManagementService.login( username, password );

   response.getWriter().println( xmlDoc.toXML() );

   return null;
}

public ModelAndView register( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
   String username = StringEscapeUtils.escapeHtml( request.getParameter( "username" ) );
   String password = StringEscapeUtils.escapeHtml( request.getParameter( "password" ) );
   Document xmlDoc = accountManagementService.register( username, password );

   response.getWriter().println( xmlDoc.toXML() );

   return null;
}

public void setAccountManagementService( AccountManagementService accountManagementService )
{
   this.accountManagementService = accountManagementService;
}
}

The URL mapping for service requests was also dead-simple:

<bean id="urlMappingDeployment" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
      <property name="mappings">
         <props>
             <prop key="/login.do">accountController</prop>
             <prop key="/register.do">accountController</prop>
             <prop key="/getInventory.do">inventoryController</prop>
             <prop key="/updateInventory.do">inventoryController</prop>
          </props>
      </property>
   </bean>

By utilizing Spring, I saved reams of code, although using a more expressive language like Groovy with Grails may have been quicker and more expressive. At any rate, I’m off to go learn about XSLT. Cheers. :)

Scala – fun, powerful JVM fun

October 12, 2009

If you’re like me, you heard about this language on the Java Posse Pod-cast (link), and you’re just now trying to figure out what all the hubbub is about. Well, Scala is functional, declaration, strongly typed (although it doesn’t feel like it), and most importantly, a JVM language. it compiles to Java classes, and with the inclusion of a single library, you can work Scala quite easily into your web application, either by design or postfixed.

Aside from ease of integration, Scala also offers many functional concepts: first-class functions, curried functions, partially applied functions, and in simple cases, tail recursion! Object-Oriented purists can continue to work as they would in Java, but those of us willing to dabble in the dark-arts can do things like this:

class MyApplication extends Application {
   println( "Hello, World!" )
}

See what’s happening? The closure between the braces is passed as a constructor argument to MyApplication, which then executes the function. It’s not that much of a convenience, but for small applications, public static void main( String[] args ) is just annoying.

Tomcat

Remember how I said Scala could run under Tomcat as easily as Java? Well, I setup a servlet on my server to proxy file downloads. Try this:

http://stefankendall.com:8080/download?url=http://stefankendall.com/files/test.txt

It’s not much to see, but the code is pretty simple!

import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import javax.servlet.ServletOutputStream
import java.net.URL
import java.io.{BufferedInputStream, PrintStream, StringWriter, PrintWriter }

class ProxyDownloadServlet extends HttpServlet
{
	override def doGet( request: HttpServletRequest,	response: HttpServletResponse )
	{
		//get the file url to download from the GET request parameter
		val fileUrl = request.getParameter( "url" );

		//if no url was provided, write that to the user
		if( fileUrl == null )
		{
			response.getWriter().println( "<html><body><p>No download url!</p></body></html>" )
			return
		}

		try
		{
			//download the file
			val inputStream = new BufferedInputStream( new URL( fileUrl ).openStream() )

			//set the content type of the response so the
			//user will be prompted to download
			response.addHeader( "Content-Type","application/octet-stream");

			//get the output stream
			val outputStream = response.getOutputStream();

                                  //data buffer
			var buffer = new Array[byte](4 * 1024)

			var bytesRead = inputStream.read( buffer )
			while( bytesRead != -1 )
			{
				outputStream.write( buffer, 0, bytesRead )
				bytesRead = inputStream.read( buffer )
			}
		}
		catch
		{
			case e => {
				println( "Attempted to download:" )
				println( fileUrl )
				e.printStackTrace()
				response.setContentType("text/html")
				outputStream.println( "<html><body><p>Bad file url!</p>" )
				outputStream.println( "<p>File: " )
				outputStream.println( fileUrl );
				outputStream.println( "</p>" )
				outputStream.println( "</body></html>" )
			}
		}
		finally
		{
			inputStream.close()
			outputStream.close()
		}
	}
}

I had some trouble getting things like String concatenation working under Tomcat (Yeah, I know.), and the tools for Scala are rather weak right now (at least the eclipse plugin), but it’s definitely not Java! There’s probably a more Scala way to do this, but that just illustrates the point: you can use as much, or little, Java-isms as you see fit. Remember that this compiles to .class files, so it can mingle with other Java servlets as easily as other Java could.

[[Objective-C prog] with: iPhone and: iTunes release]

September 16, 2009

Doesn’t that subject line look crazy? Well, in Objective-C, methods, properties, and members are accessed with maniacal brackets. This is fine, aside from the fact that you need to know how deep you’re going to chain a method call BEFORE you actually do it, as otherwise you have to go back and add the correct number of left brackets. Objective-C 2.0, as supported on the iPhone, supports dot notation, but when in Rome, I hear you use crazy bracket syntax. So, then, how does this all play out? Well, iPhone development can really be sectioned off into its constituting parts: Objective-C programming, Interface Builder, and release to the app store on iTunes.

Objective-C

Objective-C 2.0 has properties, strong typing, and memory management. Objective-C for the iPhone only has the first two. For this reason, we’re forced to deal with memory management or deal with the terrible results. In making a simple business calculator, I was able to leak 6 UI elements each time the program was run and take my 3GS iPhone down to a few MB of remaining ram in only 7 or so test runs. The solution, of course, was simply releasing the UI objects when the application was closing, but this is a significant annoyance when trying rapidly design software.

True properties, of course, with synthesized property methods, save a decent amount of time and just look nicer than having your IDE generate getters and setters.

Consider the following:

//Tester.h
@interface Tester
{
   MyClass * myClass;
}
@property MyClass * myClass;
@end

//Tester.m
@implementation Tester
@synthesize myClass;
@end

Now, [testObj myClass] calls the implicitly created getter of Tester, and [testObj setMyClass: myClass] calls the implicitly generated setter. Isn’t that cool?

iPhone Development

Aside from the Objective-C nonsense, the iPhone SDKs and Interface Builder make life pretty easy for app development. Interface Builder provides a full visual interface for designing iPhone applications, and XCode even provides an iPhone emulator with which to test applications. Sure, the emulator won’t tell you if you have a memory leak, or anything of that nature, but there are other tools to monitor such.
/* TODO: add screenshots */

iTunes and iTunes Connect

The release process to iTunes, while relatively painless, requires a wealth of information and takes about two weeks to process (at least it did for FoodWatcher, my “Hello World” iTunes application to measure weightwatchers points).

The following is required to submit an application to the app store:

  • application name
  • application version
  • 512×512 image to represent the application. This is used if the application gets “featured.”
  • 57×57 iPhone icon for the application. You can either add your own gloss or let the iPhone render it for you.
  • At least 1 screenshot of the application in progress
  • A support website for the application
  • A support email for the application
  • A list of user names/passwords if your application requires it

and for non-free applications, you need to provide full tax/bank information. The process is a bit of a hassle, but the requirements make sense given the context of iTunes and the App Store.

jQuery: Plugins.

August 19, 2009

jQuery has plugins.

Lots of them, in fact. The jQuery plugin page lists hundreds of additions to the base jquery package. These plugins make web development even easier and more glamorous than jQuery alone, doing splendid things like Show dialogs.

Now isn’t that cool? jQuery plugins let external authors write neat libraries to extend the language, much as firefox extensions improve the core of firefox. As jQuery has become the javascript go-to tool of choice, jQuery plugins have become the library tools of choice for productive, external-library-oriented developers, such as you and me. So fly, ye’ programmer, and explore the world of jQuery plugins.


 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org