How to Keep Divs the Same Height?

Equal height columns? Divs that stay the same height?

After reading this post you will have beautiful, responsive divs/columns that always stay the same height as the content grows. How will we achieve this might you ask? Through the awesomeness of Flexbox! Flexbox has 94% global support (and you can provide fallbacks easily, but that is for another post) and it has made it easier to work with divs, columns, create image galleries and complex layouts that are also responsive.

So let’s get to it, how do we use Flexbox to create responsive columns of equal height regardless of how much text/content is in each one?

HTML Structure

We will start with some HTML to define our columns. For the purpose of this example let’s create 3 divs as our columns with an image and some text inside. To help us make these look even we will also need to wrap the whole thing in a container div, so let’s add that as well. You will see why we need a container div shortly.

Example structure, amend this as needed.

See the Pen Vertically Aligned Divs by Liliana Kastilio (@lili2311) on CodePen.

Some CSS styling

So now we have our markup, let’s give it some basic styling: some background colour so we can see where our columns start and end and let’s make it a 3 column layout by fixing the width as a quick hack for now.

Example CSS, amend this as needed.

See the Pen Vertically Aligned Divs by Liliana Kastilio (@lili2311) on CodePen.

Ugly uneven columns

So at this stage we have exactly what you don’t want, 3 ugly uneven columns. So when you only have a tiny bit of content in one it stays shorter than the others. 🚫 I am sure you have already tried fixing the height of the element and I probably don’t have to say that that was a terrible idea and it looks bad anyway.

Flexbox to the rescue

What we really want is to allow the columns to breathe and grow as they need to given the amount of content in them but all stay the same height which is the height of the longest columns. This is where we can use the magic 💫 of Flexbox.

What do you need to know to use Flexbox?

Flexbox container

When working with flexbox there is always a parent container that wraps around the elements that you want to align with Flexbox.

Display Flex

This parent element must have it’s display property set to display: flex. By just setting that property we have almost fixed our problem completely!

Flex Direction

You can also set the direction in which you want the items to align, which can be row or column. In this scenario all the columns we have need to sit in one row. So we want all the immediate children of the Flex container to be in one row and therefore we need to set flex-direction: row but if we also want it to stay fully responsive and the columns to fold over to the next row when there is not enough space we can tell the container to allow wrapping with flex-wrap: wrap:

Example CSS with Flexbox

See the Pen Vertically Aligned Divs by Liliana Kastilio (@lili2311) on CodePen.

Flexbox children

For each child of a flex container (these will automatically be the direct children) we also can specify how much each child can grow and shrink given the amount of available space. So in our case we can set flex: 1; on the .col and to fully see it’s effect let’s remove everything else we added for this example to be a 3 col layout.

Example CSS with extra properties for responsiveness.

See the Pen Vertically Aligned Divs by Liliana Kastilio (@lili2311) on CodePen.

And here is the final result, 3 same height and same width columns that are responsive and without using any grids!

See the Pen Vertically Aligned Divs by Liliana Kastilio (@lili2311) on CodePen.

🔥 If you enjoyed this post then you can keep up to date with my latests blogs posts & courses by following me on Twitter and checking out my code school for some hands on guided coding practice.

It Is Okay to Feel Like Giving Up!

Getting stuck sucks 😭

One of the most demotivating things a new developer can face is getting stuck and not knowing what to do! It can be very hard to stay motivated and to know what to read and learn when you are just starting out, being stuck somewhere often means you might feel like giving up. Maybe I am not good at developing? Maybe it is easier for someone else with a different background/age? Maybe I won’t ever ‘get it’? All these things are not true, the only difference between someone who made is a developer and someone who did not is being able to push through and keep going even when you think you cannot fix whatever is wrong. Knowing when to take a break, knowing that there is always more to learn and keeping an open mind for changes. Sometimes things change because someone proved that that is the best way to it. That feeling of “I am not good enough” and “I just don’t get it!” never leaves, every developer still has bad days and those “I am stuck moments” but we simply learn how to overcome it and how to stay motivated.

Here are a few tips that help me stay motivated

These are things that help me everyday to get throguh those “stuck” moments:

1. Take a break

Often coming back in fifteen minutes or even just the next day can make all the difference. Being tired can make you miss little things

2. Try explaining your problem to someone else

And if no one is around just talk your problem through out loud. Verbalising your problem can make you realise where you went wrong. Developers sometimes have little ducks to talk to because of how often you go to ask for help and by just explaining the problem you realise what you did wrong, so not to waste anyone else’s time you can chat to the little rubber duck first 😏 Google it! Stuck somewhere? Google the problem, googling for a solution is a skill. Knowing what to put as the search term takes practice and over time you will get better at arriving directly at the right kind of problem on the internet with the exact solution you need. Be specific in your search terms.

3. If you feel that something is simply too hard, take a step back

Review what you know and what you are unsure of and try reading a little more about it to see if you can gain a clearer understanding. Being a developer you never stop learning, so if this is something you do not enjoy yet this is a chance to figure out what makes you learn well and how you can make it more interesting for yourself.

🔥 If you enjoyed this post then you can keep up to date with my latests blogs posts & courses by following me on Twitter and checking out my code school for some hands on guided coding practice.

Frontend vs Backend

Puzzled between the difference between Frontend and Backend?

When starting to learn about Web Development, I remember struggling to understand the difference between Frontend and Backend, in order to try and understand this lets first define what is a website?

What is a website?

A simple website is typically a collection of HTML documents with CSS styling applied, linked using Hyperlinks (JavaScript may also be present for user interactions and animations). Both HTML and CSS are natively understood and interpreted by the browsers and so is JavaScript. Meaning that the 3 technologies together are the building blocks of any website. These 3 technologies are the typical makeup of the websites front-end. A front end is what the user sees when visiting a website. It is the visual part you can interact with.

Backend vs Frontend

Any website can also have a backend - aka some service that lives on a server capable of communicating with the front end of the website to send it data. For example the front end may be requesting user data from a database to populate a user profile page. Front end only websites do not have a backend and do not usually have a database so are considered static. A static website means that the pages are always the same and the pages do not display differently depending on who you are, for example different users see different data in their profile page that is relevant to them. Backends are usually created for larger websites that need to handle user signups, user profiles, user messaging, payments and other useful actions. Static websites are more of a business card and simply provide information Every website has a front-end and some also have a backend.

Some reading materials to learn more about websites and the basics of the web technologies like HTTP:

  1. How the Web works
  2. HTTP Basic Introduction
  3. Frontend vs Backend
  4. Whats the difference between frontend and backend?
🔥 If you enjoyed this post then you can keep up to date with my latests blogs posts & courses by following me on Twitter and checking out my code school for some hands on guided coding practice.

Stop Wasting Time Logging Into GitHub on Command Line Every Time You Push: Just Set Up SSH Keys

1. Does GitHub always ask you for your password? There is a fix, read on :)

If you recently started using Git & Github in your workflow it is likely you are sick and tired of constantly having to type in your username and password every single time you want to push some chnages! Well that ends today as in this blog post I will show you how to tell Github to trust your laptop and just let you get on with coding without any fuss of logging in all the time.

In order for this to work we will use something called SSH keys.

2. What are SSH keys?

SSH keys are a means of identifyng yourself to a server without having to type in your username and password every time. It can be though of as a passwordless login. Instead of a user name and password the a pair of keys is used that is exchanged between your laptop and the server. They keys live on your laptop and on the other side, this way every time you talk to that server it will realise that you are already knowkn to it and who you are.

3. Do you already have SSH keys?

Before we make a new key, lets check if you have lying around already.

Windows

In command promt type in:

1
cd %userprofile%/.ssh

Now lets see if there is a key in there:

1
dir id_*

If you see and error something like “No such file or directory” then you don’t have a key and need to make one. Next section describes hwo to do this.

Mac & Linux

Open your preffered terminal and run the command below:

1
ls -al ~/.ssh

This will list all the files currently present in the ~/.ssh directory, which is a special directory where all keys are stored by default. The filenames to look out for are:

  1. id_rsa.pub
  2. id_rsa
  3. id_dsa.pub
  4. id_ecdsa.pub
  5. id_ed25519.pub

Check the content of the file that looks similar to the example above by using the cat command:

1
cat ~/.ssh/id_rsa.pub

There will be a whole lot ot stuff in that file including your email.

If you did not find anything in there, not to worry we will make a new SHH key!

4. Generate a new SSH key.

So if you found no keys form steps before then we should make one. Lets go back to the terminal and run the command that will generate us a new key:

1
ssh-keygen -t rsa -C "[email protected]"
  1. Just press Enter when prompted for a filename
  2. Create and enter a passphrase as requested.
  3. Tada you now have a shiny new key ready to be used.

Note that the ssh-keygen command is only available if you have already installed Git (for Windows that would be Git with Git Bash).

5. Adding a new SSH key to your GitHub account.

We now need to share the new key with Github in order to enjoy passwordless login when pushing code:

  1. Log in to your GitHub account
  2. Click on your profile photo (in the top right corner) → “Settings”
  3. In the sidebar click on “SSH and GPG keys” → “New SSH Key”
  4. Give it a title/name (perhaps this is the key for you work laptop)
  5. You now need to copy and paste the entirety of the key into here. So all the text your saw with your email that was generated during the previous step all of that is a key. If you had a key already, simply open the file and copy paste the entire contents into here.
  6. Save!

5. Try it out!

You can now go back to your project and try pushing some code, you should no longer be prompted for the password and username every time.

🔥 If you enjoyed this post and are keen to learn more about Git or use it in a practical project check out the courses I am working on to help a new developers get to grips with common workflows and best practices. Take a peek at the Introduction to Git & Github online course.

Frontend Automation With Grunt

1. What is Grunt?

Grunt is a JavaScript task runner. Grunt lets you automate tasks like HTML minification, copying files, compiling CSS, deploying to AWS etc.

2. Download Node.js

Grunt and Grunt plugins are installed and managed via npm the Node.js package manager. First of all if you will need to download Node.js (npm will be installed with it).

3. Basic Command Line Commands

If you have not used command line terminal before you here are some basic commands:

ls

Description: Lists the names of the files in the working directory. For more complete information use ls –alF

cd directoryname

Description: Changes the working directory to the one you named.

cd ..

Description: Brings you up one directory level.

cd

Description: Returns you to your home directory.

pwd

Description: Displays the pathname of the current directory.

mkdir newdirectoryname

Description: Makes a new directory

4. Install Grunt

  1. Open your preferred terminal or install iTerm.
  2. Install Grunt globally: instructions below will install grunt client globally on your machine, if you already have Grunt installed skip this step. For a more detailed explanation see the official documentation.
  3. Install Grunt locally: Now we will install Grunt locally specifically for this project. Go to your project folder. Replace the path after cd with the path to your folder:
1
cd Documents/workshop/

In the terminal type out the below command to get to the project folder (if you have saved the workshop folder elsewhere adjust the path):

1
npm install grunt –save-dev

5. Configure

To configure the project, within your project folder type npm init in the terminal and follow the instructions:

6. Grunt AWS Plugin

We will now install Grunt AWS Plugin. Grunt uses different plugins to perform certain tasks, in order to deploy to Amazon S3 we will use the grunt-aws-s3 plugin.

In your project folder we can install this using the command below:

1
npm install grunt-aws-s3 –save-dev

We now have the plugin installed and we can configure grunt to use this task to deploy our project without having to manually upload the files every time.

In order for us to use this plugin and deploy to S3 in the command line we need to create a file called s3settings.json, here we will keep all the login details and bucket information. This file MUST be kept secret, do not commit it to github or any other version control system. It should be excluded in .gitignorefile if you are using git. It is important to take care as if these details are made public your account may be accessed and used by someone else, leaving you with a bill to pay:

The key and secret are available in the user credentials file you downloaded when creating an IAM user. Bucket must be exactly what you called the bucket on Amazon S3 and the same for region.

The second file we need to create is Gruntfile.js this is a default file Grunt will look for locally within the project folder. Here is where we configure the tasks.

Using your text editor or command line, create a new file within the workshop folder called Gruntfile.js, the content of it should be the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-aws-s3');

grunt.initConfig({
  pkg: grunt.file.readJSON('package.json'),
  s3settings: grunt.file.readJSON('s3settings.json'),
      aws_s3: {
          options: {
              accessKeyId: '<%= s3settings.key %>',
              secretAccessKey: '<%= s3settings.secret %>',
              region: '<%= s3settings.region %>',
              uploadConcurrency: 5,
              downloadConcurrency: 5
      },
      live: {
          options: {
              bucket: '<%= s3settings.bucket %>',
              differential: true //Only uploads the files that have changed
          },
          files: [
              {expand: true, cwd: 'deploy/', src: ['**'], dest: ''},
              ]
          },
      });
  grunt.registerTask('deploy', ['aws_s3:live']);
};

Full code to copy is here.

Here we have configured the plugin to upload to Amazon S3 all files in the folder deploy, so we would now have to create this folder within the project and copy any files we want uploaded.

We have also created a task called deploy which can be run in command line within the project folder to upload all files within deploy folder to Amazon S3, to the bucket specified in the s3settings.json file.

7. Use Grunt to deploy to S3

Go to the project folder in the terminal. You can now run the deploy command by typing:

1
grunt deploy

And we are done!

Part 4: Create New IAM Users and Permissions in AWS

This is Part 4 of a tutorial post Create a Simple Website in CSS/HTML and deploy to Amazon S3.

Note: Here you can look over Part 1: HTML, Part 2: CSS and Part 3: Deploy to AWS of this tutorial.

1. Create a new User

  1. Sign in to the AWS Amazon console
  2. Click on Identity & Access Management
  3. Click on User on the left hand-side menu
  4. Click Create New User
  5. Enter username testuser
  6. Click Create
  7. Download the credentials. These will include User Name, Access Key Id, Secret Access Key. Keep these secret as they are tied to your account and can be used for malicious purposes if not kept safely. Remember that your account is tied to your credit card.

2. Set user permissions

  1. You should now see your user created in the user dashboard.
  2. Click your newly created user testuser
  3. Click on Permissions → Attach Policy

  1. Select AmazonS3FullAccess → Attach Policy:
  2. Done!

Part 3: Create a Bucket and Deploy a Website to Amazon S3

This is Part 3 of a tutorial post Create a Simple Website in CSS/HTML and deploy to Amazon S3, it is aimed at a completele beginner.

Note: Here you can look over Part 1: HTML and Part 2: CSS of this tutorial.

In this tutorial we will cover:

  1. Create a free account on Amazon S3
  2. Creating a bucket on Amazon S3
  3. Uploading your website to Amazon S3

1. Create a free account on Amazon S3

Amazon has a free tier which will be enough for most small websites.

1. Go to Amazon S3

2. Click on “Try Amazon S3 for Free”:

3. Enter your email address or phone number. Then select “I am New User” and click “Sign in using our secure server”:

4. Fill out required info:

5. Fill out credit card info

6. Confirm your identity via a call:

2. Creating a bucket on Amazon S3

1. Sign in to the Amazon console

2. Click on S3

3. Click “Create a new bucket”

4. Click “Create a new bucket”

3. Fill out the bucket name (example yourname.com)

3. Uploading your website to Amazon S3

1. Click into the bucket name you have just created

2. Select “Actions” → “Upload”

3. Click “Set Details” → “Set permissions”

4. Tick “Make everything public”

5. Click “Start Upload”

6. Select the file index.html and click “Properties”

7. Click on the link

8. Thats it! Your website is now live and accessible online via this link at any time.

If you would like to learn how to automate this deploy and make it easier for continuous development watch out for the next blog post where I will talk about using Grunt.

Part 2: Create a Simple Website in CSS/HTML and Deploy to Amazon S3

This is Part 2 of a tutorial post Create a Simple Website in CSS/HTML and deploy to Amazon S3, it is aimed at a completele beginner.

In this tutorial we will briefly cover:

  1. What is CSS?
  2. CSS Basics
  3. Create a Stylesheet
  4. Link HTML and CSS
  5. Basic CSS Properties
  6. CSS Exercises

1. What is CSS?

Cascading Style Sheets (CSS) is a style sheet language used for describing what the html elements should “look like”. It is used to describe whether an html element should be of certain height, width, if the text should be bold, text colour etc. We will try this shortly.

2. CSS Basics

This is a rule:

1
2
3
h1 {
  color: red;
}
  • This rule starts with h1, which is a selector.
  • The part inside the curly braces is the declaration.
  • color is a property.
  • red is a value.
  • color: red; is a property-value pair.
  • The ; after the property-value pair separates it from other property-value pairs in the same rule, for example:
1
2
3
4
h1 {
  color: red;
  text-align: center;
}

We will refer to those definitions throughout this class.

3. CSS Basics

When the browser reads the CSS file, it finds each selector and works out if it applies to any elements in the HTML. If it does, it uses the properties within the matching rule.

A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors. Selectors allow you to SELECT all elements that match:

  • a certain tag name e.g. <h1>
  • a certain element inside another element e.g. all <li> within a <ul>

4. Create a Stylesheet

  1. Install Sublime or use your preferred text editor
  2. Create a new file in the same folder as the index.html and name it style.css
  3. Type out the code below and save in in your style.css file:
1
2
3
4
h1 {
  color: red;
  text-align: center;
}

Here you created a rule that says: All h1 elements have the following properties: text alignment is center & the text colour is red.

Exercise: Now use the example above to do the same for <p>. Clue: create a new rule and replace h1 with p.

5. Link HTML and CSS

Now that we have our first stylesheet, we can tell the html document index.html to use the stylesheet style.css so that the browser knows what the page should look like.

  1. Add the following line in your index.html file underneath the <title> tag:
    1
    
    <link rel="stylesheet" href="style.css">
    
  2. Reload the file in the browser or open it again: Open your web browser, then press Ctrl + O (Windows) or Cmd + O (Mac) to open the file we have just updated. You should see “Hello World” and the text you added in the paragraph with the added style.

6. Basic CSS Properties

color

  • Description: this is the text colour, this is used to style elements that have text e.g. h1, p, h2.
  • Example: color: white;
  • More Info: MDN: color

background-color

  • Description: this is used to define the background color of a particular element.
  • Example: background-color: blue;
  • More Info: MDN: background-color

font-size

  • Description: this is used to set the size of a font in px or other units.
  • Example: font-size: 16px;
  • More Info: CSS font size units

background-image

  • Description: this is used to set an image as a background of an element.
  • Example: background-image: url(http://examplelink.com);
  • More Info: CSS-tricks: background-image

text-align

padding

  • Description: sets the padding of the element. See the Box Model picture below for an explanation of what padding is and how it will affect the look of the element.
  • Example: padding: 10px 10px 10px 10px; or padding: 10px;
  • More Info: MDN: padding

margin

  • Description: this is used to set the margin of the element. See the Box Model picture below for an explanation of what padding is and how it will affect the look of the element.
  • Example: margin: 10px;
  • More Info: MDN: margin
6.1 CSS Box Model

In a document, each element is represented as a rectangular box. This model describes the content of the space taken by an element. Each box has four edges:

  1. margin edge
  2. border edge
  3. padding edge
  4. content edge (in blue)

You can read more about CSS Box Model here.

5. CSS Exercises

We can add more to the style.css at this stage or later, here is a list of CSS properties available.

  1. Try out all the properties from the Basic CSS Properties section and see what they all do.
  2. You can also style the <body> element, try setting a background image on the element and see what that does.
  3. Make an image to also be a link, ie make the image clickable that will take you to a different website. Tip: you can add some elements inside of other elements,try and add an img within the a.
  4. Align left or center all the text on the page.

Part 1: Create a Simple Website in CSS/HTML and Deploy to Amazon S3

This is Part 1 of a tutorial post Create a Simple Website in CSS/HTML and deploy to Amazon S3, it is aimed at a completele beginner.

In this tutorial I will briefly cover:

  1. What is HTML?
  2. HTML Basics
  3. Create a Simple HTML Page
  4. What is HTML5 and how is it different?
  5. HTML Exercisesb

1. What is HTML?

HTML - HyperText Markup Language is the standard language used to create web pages. Web browsers can read HTML files and render them into visible web pages. HTML documents are described by HTML tags, these are enclosed in angular brackets <>. HTML tags can be considered to be “keywords” that the browser can understand and render/draw in the browser appropriately when viewing the page. Each browser has default ways of interpreting each element, these can later be “styled” to look how you prefer with the help of CSS, which will be explained a little further on.

2. HTML Basics

We will create a very basic HTML page that will load and simply display “Hello World”. It will look like this:

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
    <head>
        <title>Page title goes here</title>
    </head>
    <body>
      <h1>Hello World</h1>
      <p>This is my first website!</p>
    </body>
</html>
  • The DOCTYPE is a declaration and tells the browser which ‘language’ we are talking in so it knows how to render it.
  • The text between <html> and </html> describes an HTML document
  • The text between <head> and </head> provides information about the document
  • The text between <title> and </title> provides a title for the document
  • The text between <body> and </body> describes the visible page content
  • The text between <h1> and </h1> describes a heading
  • The text between <p> and </p> describes a paragraph

3. Create a Simple HTML Page

  1. Install Sublime or use your preferred text editor
  2. Create a new folder in your Documents folder for this workshop, let’s call it website.
  3. Now open the text editor and save an empty file called index.html, you can press Cmd + S (Mac) or Ctrl + S (WIndows)
    • index.html is a special name and this is a file that the server will look for by default when a certain url is requested (link e.g. http://website.com).
    • Each simple website is basically a “directory” of files, the index.html is the first file the web browser will access and from here you can specify how to reach other files via writing hyperlinks.
    • The default file can be configured to be called something else if required, but for the purpose of this workshop we will only concentrate on simple defaults.
  4. Type out the code below:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    <!DOCTYPE html>
    <html>
        <head>
            <title>Page title goes here</title>
        </head>
        <body>
          <h1>Hello World</h1>
          <p>This is my first website!</p>
        </body>
    </html>
    
  5. Open your web browser, then press Ctrl + O (Windows) or Cmd + O (Mac) to open the file we have just created. You should see “Hello World” and the text you added as the paragraph, something like this:

4. What is HTML5 and how is it different?

HTML5 is simply a newer version that is supported by most modern browsers. HTML5 introduced some more awesome elements/tags we can use: such as <canvas>, <video>, <audio>, <footer> and many more to bring the HTML language more in-line with modern times.

5. HTML Exercises

We can add more to the page at this stage or later, here is a list of html and new html5 tags you can use.

  1. Add an image <img>:
    • Type out the following and modify the src to point to an image you like:
      1
      
       <img src="https://www.example.com/image.png " alt="Image description">
      
    • width="100" and height="90" are optional, play around with the numbers.
    • Read more about image <img> tag and it’s use.
  2. Add a link <a> to your favourite website:
    • Type out the following and modify it to link to point your favourite website:
      1
      
       <a href="https://www.example.com ">Link Text</a>
      
    • Read more about link <a> tag and it’s use.
  3. Add a footer <footer>. These usually sit at the bottom of the page, but sometimes have to be styled to stay at the bottom if there is not enough content to fill the page:
  4. Add a comment, which says “This is my first website!”:
    • Have a look at the example below and modify it as needed:
      1
      
       <!– Comment text, this will not be visible on the page –>
      
      * Read more about comments
  5. Add an unordered list of 3 things you love (use previous examples to get the format right):
    • Unordered list is started using the tag <ul> and closed using </ul>
    • Within the list declaration mentioned above you can add in list items, these are defined by: <li> </li>
    • You can have as many list items in the unordered list as you want
    • Within each item you can add other elements, such as: paragraph, link, images, another list.
    • Play around with this one, it is very useful especially for menus
    • Read more about unordered list ul tag and it’s use

Further reading and things to try:

Technical Code Interview Prep Notes

Data Structures and Algorithms

Question 1: How do you reverse a linked list using recursion (Java)?

I found the answer on this stackoverflow post “Reversing a linked list in Java, recursively”. This can be solved answering the following questions:

  1. What is the reverse of null (the empty list)? null.
  2. What is the reverse of a one element list? the element.
  3. What is the reverse of an n element list? the reverse of the second element on followed by the first element.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 public ListNode Reverse(ListNode list) {
    // What is the reverse of null (the empty list)? null.
    if (list == null) return null;

    // What is the reverse of a one element list? the element.
    if (list.next == null) return list;

    // What is the reverse of an n element list? the reverse of the second element on followed by the first element.
    // so we grab the second element (which will be the last after we reverse it)
    ListNode secondElem = list.next;

    // bug fix - need to unlink list from the rest or you will get a cycle
    list.next = null;

    // then we reverse everything from the second element on
    ListNode reverseRest = Reverse(secondElem);

    // then we join the two lists
    secondElem.Next = list;

    return reverseRest;
}

Question 2: How do you find a length of a linked list?

Traverse through all the elements until you find the last node which points to null.

Question 3: How do you find the middle of a linked list using only one pass?

  1. Maintain two pointers as you traverse through the linked list.
  2. Increment Pointer 1 on every node and only increment Pointer 2 on every 2nd node.
  3. When you reach the end of the list, Pointer 2 will be pointing to the middle of the list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class LinkedListTest {
    public static void main(String args[]) {
    // Creating LinkedList with 4 elements including head
    LinkedList linkedList = new LinkedList();
    LinkedList.Node head = linkedList.head();
    linkedList.add( new LinkedList.Node("1"));
    linkedList.add( new LinkedList.Node("2"));
    linkedList.add( new LinkedList.Node("3"));

    // Finding middle element of LinkedList in single pass
    LinkedList.Node current = head;
    int length = 0;
    LinkedList.Node middle = head;

    while(current.next() != null){
      length++;
      if(length % 2 == 0){
          middle = middle.next();
      }
      current = current.next();
    }

    if(length % 2 == 1){
      middle = middle.next();
    }

    System.out.println("Length of LinkedList: " + length);
    System.out.println("Middle element of LinkedList : " + middle);

    }
}

Read more here.

Question 4: Does a given linked list have a loop?

This is solved similarly to the question above “Question 3: How do you find the middle of a linked list using only one pass?”:

  1. Maintain 2 pointers as you traverse through the list.
  2. Increment Pointer 1 on every node and only increment Pointer 2 on every 2nd node.
  3. If Pointer 1 and Pointer 2 point to the same node, the list has a loop.

Question 5: An integer array has numbers from 1 to 100, there is a duplicate in the array. Find the duplicate.

  1. Add all the numbers stored in the array.
  2. Find the expected sum of all the numbers if there were no duplicates. The sum is represented by a formula n(n+1)/2.
  3. Subtract the actual sum from the expected sum. The answer is the dulicate number.
  4. This works if there is 1 duplicate in the array, for multiple duplicates use a Hash Map, where the number is the key and the the occurence is the value. Any values larger than 1 will reveal the duplicates.

Question 6: What is the difference between a Stack vs a Queue?

A Stack is LIFO (Last In First Out) structure and a Queue is a FIFO (First In First Out) structure.

Question 7: What is a Binary Search Tree?

They are also sometimes called ordered or sorted binary trees, are a class of data structures used to implement lookup tables and dynamic sets. They store data items, known as keys, and allow fast insertion and deletion of such keys, as well as checking whether a key is present in a tree. In a binary search tree:

  1. Every left node is smaller than the root element.
  2. Every right node is larger than the root element.
  3. There are no duplicates in the binary search tree.

Question 8: How would you sort and array using a Bubble sort?

Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. Worst Case performance is O(n^2), best case is O(n).

  1. Start comparing first and second element array[0] and array[1].
  2. If array[0] > array[1] then swap numbers e.g. array[0] = array[1] and array[1] = array[0].
  3. Repeat with the next two element, array[1] and array[2] and so on until you reach the end of the list
  4. This is referred as one pass and at the end of first pass largest number is at last.
  5. Repeat this comparison again starting from array[0] but this time going till second last pair only array[n - 1].

In a Bubble sort we need n - 1 iteration to sort n elements at end of first iteration largest number is sorted and subsequently numbers smaller than that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var array =[13,1,24,56,23,4,3,2,7,9,10,11];

console.log("Sorted Array: " + bubbleSort(array));

function bubbleSort(a){
  var swapped = true;
  for(var i = 0; i < a.length-1; i ++){
    swapped = false;
    for(var j = 0; j < a.length-1; j ++){
      console.log(i +" " + j);
      if (a[j] > a[j+1]){
        var temp = a[j];
        a[j] = a[j+1];
        a[j+1] = temp;
        swapped = true;
      }
    }
    if(swapped === false) return a; // if no swaps have been made, the array is sorted. No need to keep looping.
    }
  return a;
}

Question 9: How would you check if a number is a palindrome?

Using a modulo we can determine if a number is a palindrome:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var number = 2332; // example number
var orig_num = number; // keep a copy of the original number
var new_num = number; // this number will change as we try to reverse the number without using strings
var check_num = 0;
var check_is_palindrome =[]; // storing all the individual numbers here  as we get them in reverse order.
// console.log("Number to check: " + number);

function isPalindrome(number) {

    if (number === 0) return true;

    var num_of_passes = 0;

    while (new_num > 0){
        num_of_passes ++;
        remainder = number % 10;
        //console.log("Remainder: " + remainder);
        new_num = (number - remainder)/10;
        //console.log("New number: "+ new_num);
        number = new_num;
        check_is_palindrome.push(remainder);
        //console.log(check_is_palindrome);
        //console.log("Num of passes: " + num_of_passes)
    }

    var final_check_num = 0; // this is to save our result after reversing the number

    for (var i = 0; i < check_is_palindrome.length; i++){
        final_check_num += check_is_palindrome[i] * Math.pow(10,num_of_passes - 1);
        num_of_passes --;
        //console.log("Final_check_num: " + final_check_num);
      }

    return orig_num === final_check_num;
}

console.log("Is number " + number " a palindrome? " + isPalindrome(number));

Question 10: Describe a Selection Sort?

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n^2) time complexity, making it inefficient on large lists. It performs worse than the similar insertion sort.

  1. Divide the list into two parts: the sublist of items already sorted and the sublist of items left to be sorted. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list.
  2. Find the smallest or largest element in the unsorted sublist.
  3. Exchange places with the leftmost unsorted item.
  4. Repeat 2 & 3 until no unsorted items left.

Question 11: Describe a Shell Sort?

The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange. It is similar to the Insertion sort that allows the exchange of items that are far apart. Worst case performance is O(n^2), best case is O(n log2 n). Picking the correct gaps is difficult, they should be reducing until the gap is 1.

Question 12: Describe an Insertion Sort?

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

  1. For each item, remove form unsorted and place in the correct place in teh sorted list or sub-list
  2. Move up all larger elements if required to place the item in the correct place.

Question 13: Describe a Quick Sort?

This is an efficient sorting algorithm. The steps are:

  1. Pick an element, called a pivot, from the array.
  2. Reorder the array 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).
  3. After this partitioning, the pivot is in its final position. This is called the partition operation.
  4. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.
  5. The last element is ussually chosen as the pivot, but this will yeild a wort case complexity on an already sorted array or on an array of identical elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var array = [13,1,24,56,23,4,3,2,7,9,10,11];

console.log("Sorted Array: " + quickSort(array));

function quickSort(a) {
  var answer = [];
  if(a.length === 1) answer=a;
  if (a.length > 1){
    console.log("quicksort " + a);
    var pivot = a[a.length-1];
    //console.log(a.length);
    var left_a = [];
    var right_a = [pivot];
    for(var i = 0; i < a.length; i++){
      //console.log("Comparing " + pivot " and a[i]= " + a[i]);
      if(pivot > a[i]){
        left_a.push(a[i]);
      }
      if(a[i] > pivot){
        right_a.push(a[i]);
      }
      console.log(left_a, right_a);
    }
    answer.push(quickSort(left_a));
    answer.push(quickSort(right_a));
  }
  return answer;

Question 14: Describe a Merge Sort?

A merge sort is an O(n log n) comparison-based sorting algorithm. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945. Conceptually, a merge sort works as follows:

  1. Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
  2. Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function merge_sort(list m)
    // Base case. A list of zero or one elements is sorted, by definition.
    if length(m) <= 1
        return m

    // Recursive case. Divide the list into equal-sized sublists.
    var list left, right
    var integer middle = length(m) / 2
    for each x in m before middle
         add x to left
    for each x in m after or equal middle
         add x to right

    // Recursively sort both sublists
    left = merge_sort(left)
    right = merge_sort(right)
    // Then merge the now-sorted sublists.
    return merge(left, right)

function merge(left, right)
    var list result
    while notempty(left) and notempty(right)
        if first(left) <= first(right)
            append first(left) to result
            left = rest(left)
        else
            append first(right) to result
            right = rest(right)
    // either left or right may have elements left
    while notempty(left)
        append first(left) to result
        left = rest(left)
    while notempty(right)
        append first(right) to result
        right = rest(right)
    return result

Question 15: Describe a Heap Sort?

Heap sort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort.

HTML, CSS and JavaScript

Question 1: Explain what are selectors in CSS?

Selectors enable selecting an element to which a style is to be applied. There are different types of selectors, like class, id, descendant, type selectors.

Question 2: Explain a CSS box model?

Each element is represented as a rectangular box. Each of these boxes is described using the standard box model. Each box has four edges: the margin edge, border edge, padding edge, and content edge.

There are two types of box model, border-box and content-box.

Question 3: What are pseudo classes and what are they used for?

Pseudo classes are similar to classes, but they are not defined in the markup. Some examples are :link, :visited, :hover, :active, :first_line. They are used to call a specific action on an element, for example changng the link colour after it is visited, or changing a link colour when it is hovered.

Question 4: How do you optimize a website’s assets?

Some of the ways to optimize assets are:

  1. Make fewer HTTP requests
  2. Use a Content Delivery Network
  3. Add an Expires header
  4. Gzip components
  5. Put CSS at the top
  6. Move scripts to the bottom
  7. Make JavaScript and CSS external
  8. Minify JavaScript
  9. Remove duplicate scripts

Question 5: What are the 3 different ways to apply CSS?

  1. Inline
  2. External
  3. Embedded/Internal

Question 6: How is the float property implemented in CSS?

Floats allow an element to be positioned horizontally, allowing elements below the floated element to flow around it. Several floating elements can be placed together to make a gallery type layout. To prevent subsequent elements from flowing around the floated element, pass in the clear property, followed by the side you wish to disable (i.e., ‘left’, ‘right’, ‘both’).

Question 7: What is the purpose of the z-index and how is it used?

The z-index helps specify the stack order of positioned elements that may overlap one another.

Question 8: What’s the difference between standards mode and quirks mode?

One prominent difference between quirks and standards modes is the handling of the CSS Internet Explorer box model bug. Another notable difference is the vertical alignment of certain types of inline content.

If the browser decides that the document is modern, it’ll render it in standards mode. This means that, as a rule, CSS is applied in accordance with the CSS2 specification. If the browser decides that the document is old-school, it’ll render it in quirks mode.

Question 9: Graceful degradation vx progressive enhancement?

Graceful degredation - making sure that everythign still works to some level in an older browser, providing with basic functionality of the site.

Progressive enhancement - starting off with the oldest browsers in mind and adding in better functionality for browsers that can handle it.

Degrading gracefully means looking back whereas enhancing progressively means looking forward whilst keeping your feet on firm ground.

Useful Resources:

  1. Mozilla Developer Network.
  2. Wikipedia.
  3. StackOverflow.
  4. Tuts+.
  5. Java Revisited Blog.
  6. Quirks Mode.
  7. Google Developers.
  8. Skilled Up
  9. Quirks vs Standard
  10. Excellent resource of front end interview questions.
  11. HTTP2