www.fatihkabakci.com

Personal Website and Computer Science TUR EN

Interview Question ZigZag Conversion

Last update: 11/20/2016 3:36:00 PM

By Fatih KABAKCI

The problem is to convert a string to a new pattern which is called zigzag that shapes characters in rows. Algorithm starts to run by asking the user that how many rows the user would like to input, then it converts the string a zigzag pattern that split all characters in rows.

Problem #6 - ZigZag Conversion

Description: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility).

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:.

Difficulty: Easy

Solution in Java

The solution can be implemented as imagining of the variable deep travels like a sinusoidal curve as increasing first from 0 to number of rows, and then again it decreases from number of rows to 0. Then, each character is stored in the related deep level during this period that looks like below.

package com.fatihkabakci.Easy.Zigzag;

/**
 * 
 * @author fkabakci
 * Problem Description: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: 
 * (you may want to display this pattern in a fixed font for better legibility)
 * 
 *  P   A   H   N
 *	A P L S I I G
 *	Y   I   R
 *
 *	And then read line by line: "PAHNAPLSIIGYIR"
 *
 *  Write the code that will take a string and make this conversion given a number of rows:
 *  
 *  string convert(string text, int nRows);
 *  
 *  convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 * 
 * Examples:
 * 
 * Input: "PAYPALISHIRING", 3
 * Output: "PAHNAPLSIIGYIR"
 * 
 * Input: "ABCDE", 3
 * Output: "AEBDC"
 * 
 * Input: "ABCDEFG", 2
 * Output: "ACEGBDF"
 * 
 * Solution:
 *
 * 1. Create 2D array to distinguish characters each other depending on which deep they belong to.
 * 2. Create index array whose length is as number of numRows to track each deep character array.
 * 3. The variable deep always travels from 0 to numRows - 1 and from numRows - 1 to 0 during the loop.
 * 4. Get each character from string and save into 2D array which stores characters with deep-element.
 * 5. Merge all elements ordering by deep level into a string and return it.
 */
public class ZigZagConversion {
	public String convert(String s, int numRows) {
		if(numRows < 2)
			return s;
		
		int deep = 0, n = s.length();
		// elements table, deep number - indexes[0],[1],[2] elements
		char[][] t = new char[numRows][n];
		// number of numRows indexes which are counter for deep elements
		int[] indexes = new int[numRows];
		boolean UP = false, DOWN = true, direction = DOWN; // start with down
		
		for (int i = 0; i < n; i++) {
			if (deep == 0)
				direction = DOWN;
			else if (deep == numRows - 1)
				direction = UP;

			t[deep][indexes[deep]++] = s.charAt(i);

			if (direction)
				deep++;
			else
				deep--;
		}

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < numRows; i++) {
			for (int j = 0; j < indexes[i]; j++) {
				sb.append(t[i][j]);
			}
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		ZigZagConversion z = new ZigZagConversion();
		System.out.println(z.convert("PAYPALISHIRING", 3));
	}
}

The algorithm time complexity is O(n). Because of 2D array, space complexity is O(n^2).

There has been no comment yet

Name:


Question/Comment
   Please verify the image




The Topics in Computer Science

Search this site for





 

Software & Algorithms

icon

In mathematics and computer science, an algorithm is a step-by-step procedure for calculations. Algorithms are used for calculation, data processing, and automated reasoning.

Programming Languages

icon

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. It can be used to create programs to control the behavior of a machine. Java,C, C++,C#

Database

icon

A database is an organized collection of data. The data are typically organized to model aspects of reality in a way that supports processes requiring information.

Hardware

icon

Computer hardware is the collection of physical elements that constitutes a computer system. Computer hardware refers to the physical parts or components of a computer such as the monitor, memory, cpu.

Web Technologies

icon

Web development is a broad term for the work involved in developing a web site for the Internet or an intranet. Html,Css,JavaScript,ASP.Net,PHP are one of the most popular technologies. J2EE,Spring Boot, Servlet, JSP,JSF, ASP

Mobile Technologies

icon

Mobile application development is the process by which application software is developed for low-power handheld devices, such as personal digital assistants, enterprise digital assistants or mobile phones. J2ME

Network

icon

A computer network or data network is a telecommunications network that allows computers to exchange data. In computer networks, networked computing devices pass data to each other along data connections.

Operating Systems

icon

An operating system is software that manages computer hardware and software resources and provides common services for computer programs. The OS is an essential component of the system software in a computer system. Linux,Windows

Computer Science

icon

Computer science is the scientific and practical approach to computation and its applications.A computer scientist specializes in the theory of computation and the design of computational systems.