Amazon Interview Question for SDE-2s


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
3
of 3 vote

public class StringReverse {

    public static void main(String[] args) {
        String input = "aabdceaaabbbcd";
        reverseWithOneCharacterOnce(input);
    }

    private static void reverseWithOneCharacterOnce(String input) {

        Set<Character> alreadyPrintedCharacter = new HashSet<Character>();
        String reversed = "";

        for (int index = input.length() - 1; index >= 0; index--) {
            Character ch = input.charAt(index);
            if (!alreadyPrintedCharacter.contains(ch)) {
                alreadyPrintedCharacter.add(ch);
                reversed = reversed + ch;
            }
        }

        System.out.println(reversed);

    }

}

- A May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Can be implemented with DS - combination of hash map & stack.
1. put data in above DS
2. While putting data in step-1, assign head with new node in HashMap which was inserted in step-1
3. after completing the iteration on the input string & putting all data in above DS using step-1& step-2, start reading data from above DS with stack.pop() operation

Run-time complexity - O(N)
Memory complexity - O(N)

- Anonymous May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

suppose k = "aabdceaaabbbcd"
temp = []
string_list = list(reversed(k))
def get_unique_with_reverse(string_list):
for i in string_list:
if not i in temp:
temp.append(i)
print "".join(temp)

- amit.barnwal09 June 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void solve(string s) {
	reverse(s.begin(), s.end());
	set<char> seen;
	string ans;
	for (auto c : s) {
		if (!seen.count(c)) {
			ans += c;
			seen.insert(c);	
		}
	}
	cout << c;
}

- Anonymous May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringReverse {

    public static void main(String[] args) {
        String input = "aabdceaaabbbcd";
        reverseWithOneCharacterOnce(input);
    }

    private static void reverseWithOneCharacterOnce(String input) {

        Set<Character> alreadyPrintedCharacter = new HashSet<Character>();
        String reversed = "";

        for (int index = input.length() - 1; index >= 0; index--) {
            Character ch = input.charAt(index);
            if (!alreadyPrintedCharacter.contains(ch)) {
                alreadyPrintedCharacter.add(ch);
                reversed = reversed + ch;
            }
        }

        System.out.println(reversed);

    }

}

- Hi May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String reversedUnique(String input)
	{
		StringBuilder sb = new StringBuilder();
		
		for(int i=input.length()-1;i>0;i--)
		{
			if(!sb.toString().contains(input.substring(i, i+1))){
				
				sb.append(input.substring(i, i+1));
			}
		}
		return sb.toString();
	}

- harsh May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String reversedUnique(String input)
	{
		StringBuilder sb = new StringBuilder();
		
		for(int i=input.length()-1;i>0;i--)
		{
			if(!sb.toString().contains(input.substring(i, i+1))){
				
				sb.append(input.substring(i, i+1));
			}
		}
		return sb.toString();
	}

- harshmighlani May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void solution(String in)
{
	HashMap<Character> hm = new HashMap<~> ();
	for(int i=in.length-1;i>0;i--)
	{
	
		Character c = in.charAt(i);
		if(!hm.containsKey(c))
		{
			hm.add(c);
			System.out.print(c);
		}	

	}
}

- skumaringuva May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. Create data-structure - hybrid of HashMap & Stack. Head = pointing to the top of the stack. Put() - put value in hash map & changes head to point to new value inserted.
2. Start iterating over the input of string
3. After completing the iteration in step-2, start stack.pop(head) & print till stack is empty.

- thakur.871 May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <bits/stdc++.h>
#include<queue>
#include<vector>
#define ll long long int
using namespace std;
class Word
{
public:
int index;
char w;
};
bool comp(Word a,Word b)
{

return (a.index > b.index);
}
int main()
{
vector<Word> v1;
unordered_map<char,int> u1;
string str="aabdceaaabbbcd";
for(int i= str.length() - 1;i>=0;i--)
{
Word obj;
obj.index=i;
obj.w=str[i];
if(u1.count(str[i])==0)
{
u1[str[i]]=1;
v1.push_back(obj);
}
}

sort(v1.begin(),v1.end(),comp);
for (int i=0;i<v1.size();i++)
{
cout<<v1[i].w;
}
return 0;
};

- Anonymous May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <bits/stdc++.h>
#include<queue>
#include<vector>
#define ll long long int
using namespace std;
class Word
{
public:
int index;
char w;
};
bool comp(Word a,Word b)
{

return (a.index > b.index);
}
int main()
{
vector<Word> v1;
unordered_map<char,int> u1;
string str="aabdceaaabbbcd";
for(int i= str.length() - 1;i>=0;i--)
{
Word obj;
obj.index=i;
obj.w=str[i];
if(u1.count(str[i])==0)
{
u1[str[i]]=1;
v1.push_back(obj);
}
}

sort(v1.begin(),v1.end(),comp);
for (int i=0;i<v1.size();i++)
{
cout<<v1[i].w;
}
return 0;
};

- Anonymous May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <bits/stdc++.h>
#include<queue>
#include<vector>
#define ll long long int
using namespace std;
class Word
{
public:
int index;
char w;
};
bool comp(Word a,Word b)
{

return (a.index > b.index);
}
int main()
{
vector<Word> v1;
unordered_map<char,int> u1;
string str="aabdceaaabbbcd";
for(int i= str.length() - 1;i>=0;i--)
{
Word obj;
obj.index=i;
obj.w=str[i];
if(u1.count(str[i])==0)
{
u1[str[i]]=1;
v1.push_back(obj);
}
}

sort(v1.begin(),v1.end(),comp);
for (int i=0;i<v1.size();i++)
{
cout<<v1[i].w;
}
return 0;
};

- bhanu870 May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Traverse the characters of the string in reverse order and use java.util.LinkedHashSet.

- RoBa May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String printReversedOnlyOnce(String s) {
		if (s == null || s.equals("")) {
			return null;
		}		
		StringBuilder sb = new StringBuilder();
		char[] c = s.toCharArray();
		Map<Character, Boolean> mapChars = new HashMap<>();
		for (int i = c.length - 1; i >= 0; i--) {
			if (!mapChars.containsKey(c[i])) {
				sb.append(c[i]);
				mapChars.put(c[i], Boolean.TRUE);
			}
		}
		return sb.toString();
	}

- guilhebl May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <bits/stdc++.h>
#include<queue>
#include<vector>
#define ll long long int
using namespace std;

int main()
{
unordered_map<char,int> u1;
string str="aabdceaaabbbcd";
for(int i= str.length() - 1;i>=0;i--)
{

if(u1.count(str[i])==0)
		{
		u1[str[i]]=1;
		cout<<str[i];

}

return 0;
};

- bhanu870 May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <bits/stdc++.h>
#include<queue>
#include<vector>
#define ll long long int
using namespace std;

int main()
{
unordered_map<char,int> u1;
string str="aabdceaaabbbcd";
for(int i= str.length() - 1;i>=0;i--)
{
		if(u1.count(str[i])==0)
		{
		u1[str[i]]=1;
		cout<<str[i];
	     }
}

return 0;	
}

- bhanu870 May 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* print all characters present in the given string only once in a revers order*/

import java.io.*;
import java.util.*;

public class SringReverseOnce {

public static void main(String args[])
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter String input: ");
String in = sc.next();

int n = in.length();
char buf[] = in.toCharArray();


for(int i=n-1;i>=0;i--)
{ int flag;
 flag =0;
	for(int j=n-1;j>=i;j--)
	{ 
		if(buf[i]==buf[j] && j!=i)
		{ flag =1;
			break;
		}
	
	}	
	
	if(flag==0)
	{System.out.print(buf[i]);}
}

}
}

- Devesh June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

define boolean array of character set with false value.
if characters ascii value location of character set is false, set it true and print character,
otherwise ignore the character.

/**
     * Print String in reverse order but without any duplicate characters 
     * Assume character set is asci characters 0 - 255
     */
    private static boolean printStringRevNoDuplicate(String str){
        int setSize = 255;
        boolean[] charSet = new boolean[setSize];
        for(int index = str.length() - 1; index >= 0; --index){
            if(!charSet[str.charAt(index)]){
                charSet[str.charAt(index)] = true;
                System.out.print(str.charAt(index));
            }
        }
        System.out.println();
        return true;

}

- Anonymous June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def solution(s):
    result = []
    table = [0] * 256
    for x in reversed(s):
        if not table[ord(x)]:
           result.append(x)
        table[ord(x)] += 1
    print(result)
    
    # Extra feature: Print the char appears only once in reversed order
    print('Print the char shows only once')
    reduced = [x for x in result if table[ord(x)] == 1]
    print(reduced)

Time complexity: O(n)

- cnhnyu June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def rev_char_set(word):
	rev_word = list(reversed(word))
	tem_list = rev_word

	result = []

	for i in rev_word:
		if i in tem_list:
			result.append(i)
			tem_list = [x for x in tem_list if x != i]

	return ''.join(result)

- Anonymous June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def rev_char_set(word):
	rev_word = list(reversed(word))
	tem_list = rev_word

	result = []

	for i in rev_word:
		if i in tem_list:
			result.append(i)
			tem_list = [x for x in tem_list if x != i]

	return ''.join(result)

- Anonymous June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String reverse(String string) {
StringBuffer s1 = new StringBuffer(string);
s1.reverse();
System.out.println(s1);
for (int i = 0; i < s1.length(); i++) {
for (int j = i + 1; j < s1.length(); j++) {
if (s1.charAt(i) == s1.charAt(j)) {
s1.deleteCharAt(j);
} else {
continue;
}
}
}
return s1.toString();
}

- Anonymous June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String reverse(String string) {
StringBuffer s1 = new StringBuffer(string);
s1.reverse();
System.out.println(s1);
for (int i = 0; i < s1.length(); i++) {
for (int j = i + 1; j < s1.length(); j++) {
if (s1.charAt(i) == s1.charAt(j)) {
s1.deleteCharAt(j);
} else {
continue;
}
}
}
return s1.toString();
}

- razo June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String reverse(String string) {
        StringBuffer s1 = new StringBuffer(string);
        s1.reverse();
        System.out.println(s1);
        for (int i = 0; i < s1.length(); i++) {
            for (int j = i + 1; j < s1.length(); j++) {
                if (s1.charAt(i) == s1.charAt(j)) {
                    s1.deleteCharAt(j);
                } else {
                    continue;
                }
            }
        }
        return s1.toString();
    }

- razo June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String reverse(String string) {
StringBuffer s1 = new StringBuffer(string);
s1.reverse();
System.out.println(s1);
for (int i = 0; i < s1.length(); i++) {
for (int j = i + 1; j < s1.length(); j++) {
if (s1.charAt(i) == s1.charAt(j)) {
s1.deleteCharAt(j);
} else {
continue;
}
}
}
return s1.toString();
}

- razo June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private char array[] = new char[26];
	private void reverseString(String str, int index) {
		if (index < 0) {
			return;
		} else {
			char sym = str.charAt(index);
			index = index - 1;
			if (array[sym - 97] == '\u0000') {
				System.out.print(sym);
				array[sym - 97] = sym;
			}
			reverseString(str, index);
		}

	}

- verma82 June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reversed_letters(string):
	outstring = ''
	for c in string[::-1]:
		if c in outstring:
			pass
		else:
			outstring += c

	print oustring

- Nate June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

$value = 'aaafffcccddaabbeeddhhhaaabbccddaaaa';
$final_array = array();
$len = strlen($value) - 1;
for ($i = $len; $i >= 0; $i--) {
$a = $value[$i];
$final_array[$a] = $value[$i];
}
echo implode('', $final_array);

- amitinfo86 June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is a C++ implementation

#include <iostream>
#include <unordered_set>
#include <string>

void printReverseUniqueString(std::string inputStr)
{
    std::unordered_set<char> uniqueChars;
    std::string uniqueString;
    for(std::string::iterator i = inputStr.end(); i!= inputStr.begin(); i--)
    {
        if(uniqueChars.count(*i) == 0)
        {
            uniqueString.push_back(*i);
            uniqueChars.insert(*i);
        }
    }
    std::cout << uniqueString << std::endl;
}

- Anonymous June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is a C++ implementation

#include <iostream>
#include <unordered_set>
#include <string>

void printReverseUniqueString(std::string inputStr)
{
    std::unordered_set<char> uniqueChars;
    std::string uniqueString;
    for(std::string::iterator i = inputStr.end(); i!= inputStr.begin(); i--)
    {
        if(uniqueChars.count(*i) == 0)
        {
            uniqueString.push_back(*i);
            uniqueChars.insert(*i);
        }
    }
    std::cout << uniqueString << std::endl;
}

- Anirudh June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Steps:
1.Go to the last of that string
2. Check a bit in int of he bit is set
3. If not set, print and set the bit.
4. repeat until the beginning.

- Rsl June 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main(int argc, char **argv)
{
   if(argc != 2)
   {
      printf("usage: %s [test_chars]\n", argv[0]);
      return 0;
   }

   char *test_chars = argv[1];
   char temp[256];

   memset(temp, 0, sizeof(temp));

   for(int i = strlen(test_chars); i >= 0; i--)
   {
      if(temp[test_chars[i]] == 0)
      {
         printf("%c", test_chars[i]);
         temp[test_chars[i]]++;
      }
   }

   printf("\n");

   return 0;
}

- sears1234 June 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{ static string StringManipulatorReverseUnique(string s)
{
char[] charArray = s.ToCharArray();
return new string(charArray.Reverse().Distinct().ToArray());
}}}

- Random Guy June 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Solution {
    public String removeDuplicateLetters(String s) {
        boolean[] validate=new boolean[300];
        StringBuilder sb = new StringBuilder();
        for(char c:s.toCharArray()){
            if(validate[c]){
                continue;
            }
            validate[c]=true;
        }
        for(int i=299;i>=0;i++){
            if(validate[i]){
                sb.append((char)i);
            }
        }
        return sb.toString();
    }

}

- Anonymous June 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* We can solve this by using HashMap or HashSet. Hope this is also one of the effective solution */

public class ReverseArrayOnlyOneCharacter {
	public static void main(String[] args) {
		String str = "aabdceaaabbbcd";
		int[] tmparr = new int[str.length()];
		for (int i = str.length() - 1; i >= 0; i--) {
			int ch = (int) str.charAt(i);
			int mod = (((ch - 97) % 26) % (str.length() - 1));
			if (tmparr[mod] == ch) {
				continue;
			} else {
				System.out.println((char)ch);
				tmparr[mod] = ch;
			}
		}
	}
}

- anand June 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String str = "aaaabbcddddccbbdaaeee";    
        int end = str.length()-1;
        String output="";

        while(str.length() !=0 && end>=0){
            if(output.indexOf(str.charAt(end)) == -1) output +=str.charAt(end);
            end--;
        }
        System.out.println(output);

- Painter Mathavan June 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int visited[255];
void print_rev(char *str, int index, int len)
{
if(index < 0)
return;
visited[(str[index])%len] = 1;
printf("%c", str[index]);
index--;
while(visited[(str[index])%len])
{

index = index-1;

}
print_rev(str, index, len);

}


int main()
{
char *str1 = "aabdceaaabbbcd";
int len = strlen(str1);
int i = 0;
for(i = 0; i<len; i++)
visited[i] = 0;

print_rev(str1, len-1, len);
return 0;
}

- Swati June 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/* I am using visited array which is just like hash table */

void print_rev(char *str, int index, int len)
{
	if(index < 0)
		return;
	visited[(str[index])%len] = 1;
		printf("%c", str[index]);
	index--;
	while(visited[(str[index])%len])
	{
		
		index = index-1;		
		
	}
	print_rev(str, index, len);

}

- Swati June 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{
void print_rev(char *str, int index, int len)
{
	if(index < 0)
		return;
	visited[(str[index])%len] = 1;
		printf("%c", str[index]);
	index--;
	while(visited[(str[index])%len])
	{
		
		index = index-1;		
		
	}
	print_rev(str, index, len);

}

- swati3458 June 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
import java.lang.*;

/* Print all the characters present in the given string only once in a reverse order.
 * Time and space complexity should not be more than o(N)
 */
/* Test : aabdceaaabbbcd => dcbae */

public class ReverseUniqueString {

    public String printReverse(String input) throws Exception {
        String msg = null;
        List<Character> charPresent = new ArrayList<Character>();
        String output = "";
        try {
            if(null != input) {
                for(int i = input.length()-1; i > 0; i--) {
                    Character c = input.charAt(i);
                    if(!charPresent.contains(c)) {
                        charPresent.add(c);
                    }
                }
            }

            for(Character c : charPresent) {
                output = output + c.toString();
            }
        } catch (Exception e) {
            msg = "Error while determining and printing reverse order of character found.";
            System.err.println(msg);
            throw new Exception(msg,e);
        }
        return output;
    }
}

/*----------------------Tests------------------------------*/

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class ReverseUniqueStringTest {
    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testGeneralScenario() throws Exception {
        ReverseUniqueString r = new ReverseUniqueString();
        String output = r.printReverse("aabdceaaabbbcd");
        Assert.assertEquals(output,"dcbae");
    }

    @Test
    public void testNullString() throws Exception {
        ReverseUniqueString r = new ReverseUniqueString();
        String output = r.printReverse(null);
        Assert.assertEquals(output,"");
    }

    @Test
    public void testAllSame() throws Exception {
        ReverseUniqueString r = new ReverseUniqueString();
        String output = r.printReverse("aaaaaa");
        Assert.assertEquals(output,"a");
    }
}

- maverick85 June 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Reverse {
	public static void main(String[] args) {
		String s = "aabdceaaabbbcd";
		char[] c = s.toCharArray();
		
		Set<String> mySet = new LinkedHashSet<String>();
		
		for(char c1 : c){
			mySet.add(String.valueOf(c1));
		}
		System.out.println(mySet);
		Comparator<String> reverse = Comparator.reverseOrder();
		
		List<String> myList = new ArrayList<String>(mySet);
		
		Collections.sort(myList, reverse);
		System.out.println(myList);
	}
}

- Sakthi June 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Reverse {
	public static void main(String[] args) {
		String s = "aabdceaaabbbcd";
		char[] c = s.toCharArray();
		
		Set<String> mySet = new LinkedHashSet<String>();
		
		for(char c1 : c){
			mySet.add(String.valueOf(c1));
		}
		System.out.println(mySet);
		Comparator<String> reverse = Comparator.reverseOrder();
		
		List<String> myList = new ArrayList<String>(mySet);
		
		Collections.sort(myList, reverse);
		System.out.println(myList);
	}

}

- Sakthi June 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void reversePrint(String value)
	{
		value = value.toUpperCase();
		int MAX_CHAR_SET=26;
		int[] charIndexer = new int[MAX_CHAR_SET];
		if(value == null || value.equals("") | value.length()==0)
			return;
		int charIdx = 0;
		for(int idx = value.length() -1 ; idx >= 0; --idx)
		{
			charIdx = getCharIdx(value.charAt(idx));
			if(charIndexer[charIdx] ==0)
			{
				System.out.print(value.charAt(idx));
				++ charIndexer[charIdx];
			}
		}
	}
	
	private int getCharIdx(char c)
	{
		return ((int)c)-65;
	}

- Harsh123 June 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <iostream>
#include<string.h>

using namespace std;

int main()
{
char s[10001];
int arr[27];
int t,i,j,k,n;
cin>>t;
while(t--)
{
cin>>s;
n = strlen(s);
for(i = 0;i<27;i++) arr[i] = 0;
for(j=n-1;j>=0;j--)
{
if(!arr[s[j] - 'a'])
{
cout<<s[j];
arr[s[j]-'a'] = 1;
}
}

}
return 0;
}

- Anonymous June 16, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <iostream>
#include<string.h>

using namespace std;

int main()
{
   char s[10001];
   int arr[27];
   int t,i,j,k,n;
   cin>>t;
   while(t--)
   {
   	cin>>s;
   	n = strlen(s);
   	for(i = 0;i<27;i++) arr[i] = 0;
   	for(j=n-1;j>=0;j--)
   	{
   		if(!arr[s[j] - 'a'])
   		{
   			cout<<s[j];
   			arr[s[j]-'a'] = 1;
   		}
   	}
   	
   }
    return 0;
}

- Anonymous June 16, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void printCharactersInReverseOrder(String iInputString) {
		char[] charArray = iInputString.toCharArray();
		String alreadyEvaluatedCharacters = "";
		for (int i = charArray.length - 1; i >= 0; i--) {
			if (!alreadyEvaluatedCharacters.contains(String.valueOf(charArray[i]))) {
				alreadyEvaluatedCharacters = alreadyEvaluatedCharacters + charArray[i];
			}
		}
		System.out.println("String in Reverse Order with characters printed only once => " + alreadyEvaluatedCharacters);
	}

- Deepak Malik June 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void printCharactersInReverseOrder(String iInputString) {
		char[] charArray = iInputString.toCharArray();
		String alreadyEvaluatedCharacters = "";
		for (int i = charArray.length - 1; i >= 0; i--) {
			if (!alreadyEvaluatedCharacters.contains(String.valueOf(charArray[i]))) {
				alreadyEvaluatedCharacters = alreadyEvaluatedCharacters + charArray[i];
			}
		}
		System.out.println("String in Reverse Order with characters printed only once => " + alreadyEvaluatedCharacters);
	}

- Deepak June 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void printCharactersInReverseOrder(String iInputString) {
		char[] charArray = iInputString.toCharArray();
		String alreadyEvaluatedCharacters = "";
		for (int i = charArray.length - 1; i >= 0; i--) {
			if (!alreadyEvaluatedCharacters.contains(String.valueOf(charArray[i]))) {
				alreadyEvaluatedCharacters = alreadyEvaluatedCharacters + charArray[i];
			}
		}
		System.out.println("String in Reverse Order with characters printed only once => " + alreadyEvaluatedCharacters);
	}

- Deepak Malik June 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C# solution...

public static void PrintUniqueCharsInReverseOrder(string s)
        {
            List<char> list = new List<char>();

            for(int i=s.Length-1; i >= 0; i--)
            {
                if(list.Contains(s[i]))
                {
                    continue;
                }
                else
                {
                    list.Add(s[i]);
                }
            }

            foreach(char c in list)
            {
                Console.Write(c);
            }
            Console.WriteLine();
        }

- Jeanclaude June 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringReversePrint {

    public static void main(String[] args){
        printUniqueReverse("aaaabbfbccaaeeaaaff"); //faecb
    }

    public static void printUniqueReverse(String word){

        char[] cword = word.toCharArray();

        int[] tab = new int[256];

        StringBuilder sb = new StringBuilder();

        for(int i=(cword.length -1); i>=0;i--){

            char c = cword[i];

            if(tab[c] == 0){
                sb.append(c);
                tab[c] = 1;
            }

        }
        System.out.println(sb.toString());
    }

}

- fabien June 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{
bool set[128] = { false };
string str = { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbcccaabbcc" };
int length = str.length();
int endIndex = length - 1;

while (endIndex >= 0)
{
if (!(set[str.at(endIndex) - 'a']))
{
cout << str.at(endIndex);
set[str.at(endIndex) - 'a'] = true;
}
endIndex--;
}
}}

- SinghIsKing June 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

bool set[128] = { false };
	string str = { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbcccaabbcc" };
	int length = str.length();
	int endIndex = length - 1;
	
	while (endIndex >= 0)
	{
		if (!(set[str.at(endIndex) - 'a']))
		{
			cout << str.at(endIndex);
			set[str.at(endIndex) - 'a'] = true;
		}
		endIndex--;
	}

- SinghIsKing June 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ReverseString {

	public static void main(String[] args) {
		String input = "aabdceaaabbbcd";
		reverseWithUniqueCharacterSet(input);
	}

	public static void reverseWithUniqueCharacterSet(String input) {
		
		LinkedHashSet<Character> output = new LinkedHashSet<Character>();
		char[] inputCharArray=input.toCharArray();		
		for(int i=inputCharArray.length-1; i>=0;i--){			
			if(output.add(inputCharArray[i])){
				System.out.print(inputCharArray[i]);
			}
		}
	}

}

- teji.catia June 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assuming we only have lowercase a-z (We can extend this for all ASCII easily)
Following code has O(n) time and constant space. Space is Actually O(26) which is constant.

public class Test {
	
	public static void printOnceReverse(char[] s) {
		if(s.length == 0) return;
		
		boolean[] flag = new boolean[26];
		int i;
		
		for(i=0; i<s.length; i++) {
			int index = s[i] - 'a';
			flag[index] = true;
		}
		
		for(i=s.length-1; i>=0; i--) {
			int index = s[i] - 'a';
			if(flag[index] == true) {
				System.out.print(s[i]);
				flag[index] = false;
			}
		}
		System.out.println();
		
	}


	public static void main(String[] args) {
		printOnceReverse("aabdceaaabbbcd".toCharArray());
		printOnceReverse("aaaabbcddddccbbdaaeee".toCharArray());
		printOnceReverse("aaafffcccddaabbeeddhhhaaabbccddaaaa".toCharArray());

	}

}

- CodeNameEagle July 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void printReverse(String x){
		
		for(int i= x.length()-1;i>=0;i--){
			if(array[(byte)x.charAt(i)-97]==0){
				array[(byte)x.charAt(i)-97]=1;
				System.out.print(x.charAt(i));
			}
		}
	}

- Akash Bhartiya July 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

j=[]
def rev(s):
for i in reversed(s):
if i not in j:
j.append(i)
print ''.join(j)
d=rev('fjdcbkgjgh')]

- nandini July 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String reverse(String param) {
        
        StringBuilder buf = new StringBuilder();
        
        for(int i = param.length(); i > 0; i--) {
            char ch = param.charAt(i-1);        
            if (buf.indexOf(ch + "") == -1)
                buf.append(ch);
        }
        
        return buf.toString();
    }
    
    public static void main(String[] args) {
        System.out.println(reverse("aaaabbbbddddeeeewwww"));
    }

- Sunil July 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package amazon;

public class PrintAllStringInReverseWhichOccursOnlyOnce {
    public static void main(String[] args) {
        char[]c = "aabdceaaabbbcd".toCharArray();
        int[] temp = new int[128];
        for(char x :c){
            temp[x]++;
        }
        for(int i=c.length-1;i>=0;i--){
            if(temp[c[i]]>0){
                System.out.print(c[i]);
                temp[c[i]]=0;
            }
        }
    }
}

- Abhinaw Bhagat July 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
public class StringAmazon {
	public static void main(String args[]){

		String inputStr;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the String");
		inputStr=sc.nextLine();

		StringAmazon sa =new StringAmazon();
		System.out.println(sa.reverseString(inputStr));

	}

	private String reverseString(String str){
		//String output = null;
		StringBuilder sbr = new StringBuilder();
		if(str.length()==0)
			return null;

		if(str.length()==1)
			return str;

		for(int i=str.length()-1; i>0; i--){
			if(str.charAt(i)!=str.charAt(i-1)){
				sbr=sbr.append(str.charAt(i));
				
			}
			
		}
		sbr.append(str.charAt(0));
		return sbr.toString();

	}
}

- sahilchalke3 August 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//============================================================================
// Name        : StringPrintReverseOnlyOnce.cpp
// Author      : Nitish Raj, Scientist, DRDO, raj.nitp@gmail.com
// Version     :
// Copyright   : Your copyright notice
// Description : StringPrintInReverseMannerWithNoDuplicate, Ansi-style
//============================================================================

#include <bits/stdc++.h>
#include <tr1/unordered_map>
using namespace std;

int main()
{

	typedef tr1::unordered_map<char,int> charmap;

	charmap _map;
	string _str="aaaabbbbgggggffffafffbuuaaiiiiaaa";

	int str_size = _str.length();
	while(str_size>0){
		if(!_map.count(_str[str_size-1])){
			_map.insert(pair<char,int>(_str[str_size-1],1));
			cout<<_str[str_size-1];
		}


		str_size--;
	}

	/*cout<<endl;

	charmap::hasher fn = _map.hash_function();

	std::cout << "a: " << fn ('a') << std::endl;
	std::cout << "i: " << fn ('i') << std::endl;
	std::cout << "u: " << fn ('u') << std::endl;
	std::cout << "b: " << fn ('b') << std::endl;
	std::cout << "f: " << fn ('f') << std::endl;
	std::cout << "g: " << fn ('g') << std::endl;


	charmap ::iterator itr = _map.begin();
	while(itr != _map.end())
	{
		cout<<itr->first;
		itr++;
	}
*/
	return 0;
}

- raj.nitp@gmail.com August 05, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverse_unique_strings(a):
temp = {j:i for i,j in enumerate(a)}
t = temp.keys()
t.sort()
t.reverse()
print reduce(lambda x,y :x+y, t)

reverse_unique_strings("aaavvvcccdeaaefe")

- mkdivis07@gmail.com September 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverse_unique_strings(a):
	temp = {j:i for i,j in enumerate(a)}
	t = temp.keys()
	t.sort()
	t.reverse()
	print reduce(lambda x,y :x+y, t)

reverse_unique_strings("aaavvvcccdeaaefe")

- mkdivis07 September 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverse_unique_strings(a):
temp = {j:i for i,j in enumerate(a)}
t = temp.keys()
t.sort()
t.reverse()
print reduce(lambda x,y :x+y, t)

reverse_unique_strings("aaavvvcccdeaaefe")

- mkdivis07 September 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void reverseString() {
		String input = "aabdceaaabbbcd";
		Set<Character> print = new LinkedHashSet<Character>();
		for (int i = input.length() - 1; i >= 0; i--) {
			print.add(input.charAt(i));
		}
		for (Iterator iterator = print.iterator(); iterator.hasNext();) {
			System.out.println((Character) iterator.next());
		}
	}

- thangarebel November 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

wer

- Anonymous February 10, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void PrintAlphabetsOnce(char *str) {
static int flags = 0;
if ((NULL == str) || (*str == '\0')) {
return;
}

PrintAlphabetsOnce(str + 1);

if (!(flags & (1 << *str - 'a'))) {
flags |= (1 << *str - 'a');
cout << *str << " ";
}

cout << endl;
}

- Anonymous February 10, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void PrintAlphabetsOnce(char *str) {
    static int flags = 0;
    if ((NULL == str) || (*str == '\0')) {
        return;
    }
    
    PrintAlphabetsOnce(str + 1);
    
    if (!(flags & (1 << *str - 'a'))) {
        flags |= (1 << *str - 'a');
        cout << *str << " ";
    }
    
    cout << endl;

- Anonymous February 10, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static StringBuffer printStringRevOnce(String string) {
		StringBuffer sb = new StringBuffer();
		for (int i=string.length()-1; i>=0 ; i--) {
			if (sb.toString().lastIndexOf(string.charAt(i))<0) {
				sb.append(string.charAt(i));
			}
		}
		return sb;
	}

- Onkar Ganjewar February 19, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static String uniqueCharsReversed(String str){
		
		boolean[] chars = new boolean[26];
		StringBuilder sb = new StringBuilder();
		
		for(int i=str.length()-1;i>=0;i--){
			
			if(!chars[str.charAt(i)-'a']){	
				sb.append(str.charAt(i));
				chars[str.charAt(i)-'a']=true;
			}
		}
		return sb.toString();
	}

- Anonymous June 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static String uniqueCharsReversed(String str){
		
		boolean[] chars = new boolean[26];
		StringBuilder sb = new StringBuilder();
		
		for(int i=str.length()-1;i>=0;i--){
			
			if(!chars[str.charAt(i)-'a']){	
				sb.append(str.charAt(i));
				chars[str.charAt(i)-'a']=true;
			}
		}
		return sb.toString();
	}

|

- ag91375 June 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python : Used Stack and Dictionary. Complexity O(N)

s1 = 'aabdceaaabbbcd' 
#output = dcbae 

s2 = 'aaaabbcddddccbbdaaeee' 
#output = eadbc 

s3 ='aaafffcccddaabbeeddhhhaaabbccddaaaa' 
#output = adcbhef 

def check(s1):
	len1 = len(s1)
	if len1 <= 1:
		return s1

	dict1 = {}
	count = 0
	list1 = []
	for i in range(len1-1,0,-1):

		if s1[i] in dict1:

			dict1[s1[i]] = count
			count += 1
		else:
			dict1[s1[i]] = count
			count += 1
			if s1[i] not in list1:
				list1.append(s1[i])

	print dict1
	print list1


	s2 = ''

	for items in list1:
		s2 = s2 + items

	print s2


check(s3)

- koolkhush February 09, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def print_in_reverse(s):
	if not s: return s
	n = len(s)-1
	dic = dict() # space O(26) ==> O(1)
	res = []
	for i in xrange(n, -1, -1):
		ch = s[i]
		if not dic.get(ch, False):
			res.append(ch)
			dic[ch] = i

	return ''.join(res)

- Jiwan Khatiwada July 05, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def print_in_reverse(s):
	if not s: return s
	n = len(s)-1
	dic = dict() # space O(26) ==> O(1)
	res = []
	for i in xrange(n, -1, -1):
		ch = s[i]
		if not dic.get(ch, False):
			res.append(ch)
			dic[ch] = i

	return ''.join(res)

- nawijj July 05, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More