Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
O(n) complexity.
#include <stdio.h>
void printPattern (char* str, int len) {
int row = (len%3 == 0) ? (len/3) : ((len/3)+1) ;
int i ;
for ( i = 0 ; i < row ; i ++ ) {
printf ( "%c", str[i] ) ;
printf ( " %c", str[i+row] ) ;
if ( (i+(row<<1)) < len )
printf ( " %c", str[i+(row<<1)] ) ;
printf ("\n") ;
}
}
int main () {
char str[] = {'a','b', 'c', 'd', 'e', 'f' , 'g', 'h', 'i', 'j'} ;
printPattern (str, sizeof(str)/sizeof(str[0])) ;
return 0;
}
here is the solution with o(n^2) since it involves rows and columns, I am not sure if it can be done with less complexity.
#include <stdio.h>
/*
* Print List as columns
*/
void main()
{
char vals[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
int length = sizeof(vals)/sizeof(char);
int rows = length/3;
int remainder = length%3;
if (remainder > 0)
{
rows++;
}
int i=0, j;
for (i=0; i<rows ; i++)
{
for (j=i ; j<=length ; j+=rows)
{
printf("%c", vals[j]);
}
printf("\n");
}
}
public class PrintListInColumns {
public static void main(String[] args) {
char arr[] ={'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
char brr[][]= new char[4][3];
int k=0;
for(int j=0;j<3;j++)
{
for(int i=0;i<4;i++)
{
if(i>=2&&j>1)
{
brr[i][j]=' ';
}
else
{
brr[i][j]=arr[k];
k++;
}
}
}
for(int j=0;j<brr.length;j++)
{
for(int i=0;i<brr[j].length;i++)
{
System.out.print(brr[j][i]+" ");
}
System.out.println(" ");
}
}
}
public class PrintByColumn {
public static void print(int[] input, int row){
String[] s = new String[row];
for(int i=0; i<input.length;i++){
if(s[i%row]==null){
s[i%row]=input[i]+" ";
}else{
s[i%row] +=input[i]+" ";
}
}
for(String str:s){
System.out.println(str);
}
}
public static void main(String[] args){
print(new int[]{1,2,3,4,5,6,7,8,9}, 4);
}
}
Complexity: O(n)
- cobra July 15, 2012