How both code different each other?, when run code1 given TLE error but second not give . both 0(n) based solution
code1
public static String countSort(String arr)
{
int freq[] = new int[26];
char a[] = new char[arr.length()];
for(int i=0;i<arr.length();i++)
{
freq[arr.charAt(i)-'a']++;
}
for(int i=1;i<26;i++)
freq[i]+=freq[i-1];
String ans="";
for(int i=arr.length()-1;i>=0;i--)
{
a[freq[arr.charAt(i)-'a']-1] = arr.charAt(i);
freq[arr.charAt(i)-'a']=freq[arr.charAt(i)-'a']-1;
}
for(int i=0;i<a.length;i++)
{
ans+=a[i];
}
return ans;
}
code 2
public static String countSort(String arr)
{
int freq[] = new int[26];
char a[] = new char[arr.length()];
for(int i=0;i<arr.length();i++)
{
freq[arr.charAt(i)-'a']++;
}
for(int i=1;i<26;i++)
freq[i]+=freq[i-1];
String ans="";
for(int i=arr.length()-1;i>=0;i--)
{
a[freq[arr.charAt(i)-'a']-1] = arr.charAt(i);
freq[arr.charAt(i)-'a']=freq[arr.charAt(i)-'a']-1;
}
return new String(a);
}
Expected Time Complexity: O(N). Expected Auxiliary Space: O(N).