## What recursive T(N) function typically can conclude the algorithm is O(n ^ 2), O(n log n), O(n), and O(log n)?

Is it true that some common forms of recursive T(n) can give the following conclusions?

When

T(n) = T(n/c) + b    where c is a constant > 1, b is any constant 

then the algorithm is O(log n).

When

T(n) = T(n/c) + T(n/d) + bn   where c and d are constants > 1, b is any constant 

then the algorithm is O(n log n).

When

T(n) = T(n - c) + bn   where c, b are constants > 1 

then the algorithm is O(n2) and seems like many useful algorithms don’t have this pattern and O(n2) is not often seen in classical algorithms.

I have seen the form:

T(n) = T(n/c) + T(n/d) + O(n)   where c and d are constants > 1 

for the selection / median algorithm and it is concluded that the algorithm is O(n) but isn’t the T(n) the same as formula 2 for O(n log n) above?

## Minimize cost of recursive pairwise sums: how to prove the greedy solution works?

The problem is in this other question.

Why does this always work? It’s not clear to me how one would use induction.

For $$n = 3$$, a quick calculation shows it works, however, I think it generalizes well.

## Recursive Bubble Sort Complexity

I have this code for a recursive bubble sort:

def bubble_sort_recursive(list_):     global counter     for i in range(len(list_)):         counter += 1         try:             if list_[i + 1] < list_[i]:                 list_[i], list_[i + 1] = list_[i + 1], list_[i]                 bubble_sort_recursive(list_)         except IndexError:             continue     return list_ 

The counter is initialized with zero outside the function, so I can count the number of times the elements were iterated.

I was told that the complexity of bubble sort is O(N^2). But when I run with a reversed list (worst case) with size 3, the counter finishes with the value 12, shouldn’t it be 9?

The same happens for other sizes: 4 -> 28 5 -> 55

What is happening?

## Why is my iterative solution slower than a recursive solution?

I am trying to obtain a solution for this question https://www.spoj.com/problems/COINS/.

But oddly enough, my iterative solution:

#include <iostream> using namespace std;  int main() {     int n;     while(cin >> n){         long long int dp[n+2];         dp[0]=0;         for(long long int i=1; i<=n; i++)             dp[i]=max(dp[i/2]+dp[i/3]+dp[i/4], i);         cout << dp[n] <<endl;     }     return 0; } 

gets a TLE, while the recursive solution for this(Not mine) gets accepted in no time:

#include <cstdio> #include <map> #include <algorithm>  using namespace std;  map<int, long long> dp;  long long f(int n){     if(n==0) return 0;      if(dp[n]!=0) return dp[n];      long long aux=f(n/2)+f(n/3)+f(n/4);      if(aux>n) dp[n]=aux;     else dp[n]=n;      return dp[n]; }  int main(){         int n;      while(scanf("%d",&n)==1) printf("%lld\n",f(n));      return 0; } 

Shouldn’t it be the opposite? I am genuinely confused. Please tell me how I can improve the first code.

## Representing a recursive Structure in OOP

I want to represent an Edifact message in an OOP Language. An Edifact message has the following structure:

message      :=  [ ( segment | segmentgroup ) ] segmentgroup : = [ ( segment | segmentgroup ) ] 

In words: A message is a list of segments or segmentsgroups. Segments are the base element, segmentgroups have a recursive definition ( the same as the message).

How do I represnt this in OOP? I could introduce an artfical element, say messagenode, and make both segment and segmentgourp inherit from this element. Then message woiuld be an array of messagenode. But that does’t feel right for me, because when I process a message, would always do type checks, as i process them completly different. Is there a better solution?

## Exiting Recursive Function C++

In the following function IsDoubleString(),if res is true then it shouldn’t call IsDoubleString(), I debugged the code but I am unable to understand that once it hit the line returns res; why does the control go inside the if(!res) condition? Shouldn’t it be directly returning the res value to the main function?

bool IsDoubleString(map<char,int> Word) {     bool res = true;     for (auto itr = Word.begin(); itr != Word.end(); ++itr)     {         if (itr->second % 2 != 0)         {             itr->second -= 1;             res = false;             break;         }     }     if (!res)     {         IsDoubleString(Word);     }     //return res; should directly return the value to main() but while      //debugging I      //found it goes inside the if(!res) above this return res; line     return res; }  int main() {     map<char, int> WordMap;     WordMap.insert({ 'w', 2 });     WordMap.insert({ 'o', 1 });     IsDoubleString(WordMap) ? cout << "Yes" << endl : cout << "No" << endl;     return 0; }  /*The code aims to print Yes or No if from the given string we can divide the string symmetrically, Entered string is P, A+B = P and A=B Print Yes and if we can't divide the string such A is not equal to B we will delete the characters so that we wilL try to make A equal to B 1. wow - Yes, we have to delete o, then A = B = w; P =A+B 2. lala - Yes A = B = la; P = A+B 3. a - No, since we can divide a string of size 1 4. ab - No, if A=a,B=b; A!=B or viceversa So, the following code works in such a way , We entering a string which is being entered in WordMap, in this scenario we are entering wow string which is inserted in the WordMap and it works perfectly but as soon it returns res; the control goes inside if(!res) but this shouldn't happen as res is true*/ 

## Recursive conversion from ExpandoObject to Dictionary – rework

Because my original question was lacking many details, I have been advised to ask a new question.
I will repeat the important parts of the original question and add examples etc to hopefully make it clear.

For my blazor library which is a modification of this awesome library I have to convert an ExpandoObject into a Dictionary<string, object> since ExpandoObjects aren’t serialized properly in the newest preview versions of dotnet-core. See my question related to this for more details.

For this new question I have already improved my code with recommendations from this and this answer on my previous question.

This is my current (and hopefully already better) approach. I have added summaries to more clearly show my intent but I’m sure these could be improved as well since I’m not very good at documenting my code.
Also worth mentioning if it’s not clear, these changes did not affect the program and everything still works.

/// <summary> /// This method is specifically used to convert an <see cref="ExpandoObject"/> with a Tree structure to a <see cref="Dictionary{string, object}"/>. /// </summary> /// <param name="expando">The <see cref="ExpandoObject"/> to convert</param> /// <returns>The fully converted <see cref="ExpandoObject"/></returns> private static Dictionary<string, object> ConvertExpandoObjectToDictionary(ExpandoObject expando) => RecursivelyConvertIDictToDict(expando);  /// <summary> /// This method takes an <see cref="IDictionary{string, object}"/> and recursively converts it to a <see cref="Dictionary{string, object}"/>.  /// The idea is that every <see cref="IDictionary{string, object}"/> in the tree will be of type <see cref="Dictionary{string, object}"/> instead of some other implementation like <see cref="ExpandoObject"/>. /// </summary> /// <param name="value">The <see cref="IDictionary{string, object}"/> to convert</param> /// <returns>The fully converted <see cref="Dictionary{string, object}"/></returns> private static Dictionary<string, object> RecursivelyConvertIDictToDict(IDictionary<string, object> value) =>     value.ToDictionary(         keySelector => keySelector.Key,         elementSelector =>         {             // if it's another IDict just go through it recursively             if (elementSelector.Value is IDictionary<string, object> dict)             {                 return RecursivelyConvertIDictToDict(dict);             }              // if it's an IEnumerable check each element             if (elementSelector.Value is IEnumerable<object> list)             {                 // go through all objects in the list                 // if the object is an IDict -> convert it                 // if not keep it as is                 return list                     .Select(o => o is IDictionary<string, object>                         ? RecursivelyConvertIDictToDict((IDictionary<string, object>)o)                         : o                     );             }              // neither an IDict nor an IEnumerable -> it's fine to just return the value it has             return elementSelector.Value;         }     );  

Something I didn’t mention in detail is why I need this conversion in the first place. This is also the reason this answer probably wont help :/

I’ll explain it with a simplified example:

public void Demo() {     SomeConfig config = new SomeConfig     {         Options = new SomeOptions   // it can contain complex types         {             SomeInt = 2,            // it can contain primative types             SomeString = null,                   Axes = new List<Axis>   // it can contain complex lists             {                 new Axis(),                 new Axis                 {                     SomeString = "axisString"                 }             }         },         Data = new SomeData         {             Data = new List<int> { 1, 2, 3, 4, 5 },     // it can contain primative lists             SomeString = "asdf",             SomeStringEnum = MyStringEnum.Test          // it can contain objects with custom parsing (for JSON.NET, not the parsing that's done when invoking the JS sadly         }     };      // now there are three options for invoking the javascript (I invoke it using IJSRuntime.InvokeAsync)      // this does not work because there are still nulls and the StringEnum will be parsed as an object instead of string (     // json.net parses it correctly because of the custom converter but .net does not as it just sees an object)     InvokeJavascript(config);      // the nulls are gone and the StringEnum is parsed correctly but      // this does not work because .Net (NOT JSON.NET) has to convert the parameter to json which is not possible if the object is an ExpandoObject     InvokeJavascript(StripNulls(config));      // this does work because .Net can serialize a Dictionary but not an ExpandoObject.      // the nulls are still gone and the StringEnum is parsed correctly     InvokeJavascript(ConvertExpandoObjectToDictionary(StripNulls(config)));  }  /// <summary> /// Returns an object that is equivalent to the given parameter but without any null members. /// <para>This method is necessary because of the custom parsing for string enums and because for server-side blazor projects,  /// the interop doesn't work if there are null values (no idea why, this really should be fixed sometime in the future)</para> /// </summary> private static ExpandoObject StripNulls(SomeConfig chartConfig) {     // Serializing with the custom serializer settings remove null members     // this cleanChartConfigStr doesn't contain a single null value and also the StringEnums are parsed as strings instead of objects because I use JSON.NET here     string cleanChartConfigStr = JsonConvert.SerializeObject(chartConfig, JsonSerializerSettings);      // Get back an ExpandoObject with the clean config - having an ExpandoObject allows us to add/replace members regardless of type     // which is necessary for preserving the DotNetObjectRefs (see below). Also if it were to be parsed back to the original Type (SomeConfig)      // the null values would return (and the string enums would throw errors since I've only implemented writing json but that could be fixed)     dynamic clearConfigExpando = JsonConvert.DeserializeObject<ExpandoObject>(cleanChartConfigStr, new ExpandoObjectConverter());      /*      * There are DotNetObjectRefs in the config which are manually being restored here and assigned to the right property in the dynamic config      */      return clearConfigExpando; }  // serializer settings for json.net to ignore all the null values and use the CamelCaseNamingStrategy private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings {     NullValueHandling = NullValueHandling.Ignore,     ContractResolver = new DefaultContractResolver     {         NamingStrategy = new CamelCaseNamingStrategy(true, false)     } };  

I can show you the difference when looking at the json that get produced when invoking the javascript with different objects:

Directly invoking the javascript with the SomeConfig instance from the demo results in this json code being used in the javascript:

{     "options": {         "someInt": 2,         "someString": null,         "axes": [             {                 "someString": null             },             {                 "someString": "axisString"             }         ]     },     "data": {         "data": [             1,             2,             3,             4,             5         ],         "someString": "asdf",         "someStringEnum": {}     } } 

First parsing it with custom parsing (using JSON.NET), then reading it back as ExpandoObject (using JSON.NET) and converting that to a Dictionary<string, object> results in the following json being used:

{     "options": {         "someInt": 2,         "axes": [             {},             {                 "someString": "axisString"             }         ]     },     "data": {         "data": [             1,             2,             3,             4,             5         ],         "someString": "asdf",         "someStringEnum": "someTestThing"     } } 

Note that both of these json string were not produced by json.net but by .net itself when invoking the javascript using IJSRuntime.InvokeAsync.

The json of the second option is in this example exactly the same as the intermediate json cleanChartConfigStr in the StripNulls method. This cleanChartConfigStr does not contain the functions and DotNetObjectRefs which are added to the ExpandoObject later on in the StripNulls method. When using JSON.stringify to print the json-string of that ExpandoObject (that’s the json-string I showed you), you won’t see those functions/DotNetObjectRefs either but this time because JSON.stringify doesn’t print them, not because there are non-existent.
I mention this because otherwise you might think that the cleanChartConfigStr as json-object would be equal to the json-object produced by the ExpandoObject which is not true (because of those functions and DotNetObjectRefs).

I feel like this part was confusing, I hope you understand what’s going on.

Here are the remaining classes needed for the code to compile:

class SomeConfig {     public SomeOptions Options { get; set; }     public SomeData Data { get; set; } }  class SomeOptions {     public int SomeInt { get; set; }      public string SomeString { get; set; }      public List<Axis> Axes { get; set; } }  class SomeData {     public List<int> Data { get; set; }      public string SomeString { get; set; }      public MyStringEnum SomeStringEnum { get; set; } }  class Axis {     public string SomeString { get; set; } }  [JsonConverter(typeof(JsonStringEnumConverter))] class MyStringEnum {     public static MyStringEnum Test => new MyStringEnum("someTestThing");       private readonly string _value;     private MyStringEnum(string stringRep) => _value = stringRep;     public override string ToString() => _value; }  class JsonStringEnumConverter : JsonConverter<MyStringEnum> {     public sealed override bool CanRead => false;     public sealed override bool CanWrite => true;      public sealed override MyStringEnum ReadJson(JsonReader reader, Type objectType, MyStringEnum existingValue, bool hasExistingValue, JsonSerializer serializer)     {         throw new NotImplementedException("Don't use me to read JSON");     }      public override void WriteJson(JsonWriter writer, MyStringEnum value, JsonSerializer serializer)     {         // ToString was overwritten by StringEnum -> safe to just print the string representation         writer.WriteValue(value.ToString());     } } 

Now, I have put a lot of time and effort in this question and I hope now there’s enough detail. As already mentioned, the real code (not this small demo example) is available on github. The most important file for this question would be ChartJsInterop.cs.

Once again I’m mostly interested in the recursive solution to convert those ExpandoObjects. However I’m happy for any critisism so please also mention every small thing that bugs you 🙂

## Recursive conversion from ExpandoObject to Dictionary

For my blazor library which is a modification of this awesome library I have to convert an ExpandoObject into a Dictionary<string, object> since ExpandoObjects aren’t serialized properly in the newest preview versions of dotnet-core. See my question related to this for more details.

My current approach goes as follows:

Dictionary<string, object> ConvertDynamicToDictonary(IDictionary<string, object> value) {     return value.ToDictionary(         p => p.Key,         p =>         {             // if it's another IDict (might be a ExpandoObject or could also be an actual Dict containing ExpandoObjects) just go through it recursively             if (p.Value is IDictionary<string, object> dict)             {                 return ConvertDynamicToDictonary(dict);             }              // if it's an IEnumerable, it might have ExpandoObjects inside, so check for that             if (p.Value is IEnumerable<object> list)             {                 if (list.Any(o => o is ExpandoObject))                 {                     // if it does contain ExpandoObjects, take all of those and also go through them recursively                     return list                         .Where(o => o is ExpandoObject)                         .Select(o => ConvertDynamicToDictonary((ExpandoObject)o));                 }             }              // neither an IDict nor an IEnumerable -> it's probably fine to just return the value it has             return p.Value;         }      ); } 

This works fine but I’m not sure about the IEnumerable part. If I omit the list.Any check it still works fine. New version (only write the IEnumerable part changed):

// if it's an IEnumerable, it might have ExpandoObjects inside, so check for that if (p.Value is IEnumerable<object> list) {     // take all ExpandoObjects and go through them recursively     return list         .Where(o => o is ExpandoObject)         .Select(o => ConvertDynamicToDictonary((ExpandoObject)o)); } 

I have also tried using IEnumerable<ExpandoObject> instead of just IEnumerable<object> to see if that would work and maybe be cleaner and I can confirm that that does not work (throws error).

What I would like to know now is, if it’s a good idea to omit the Any check and which option is more performant (and why) and/or cleaner.
Also please mention every small thing that bugs you, I always want to make it as perfect as possible 🙂

I first wanted to post this on StackOverflow but I think it fits better on here – correct me if I’m wrong.

## Is a language whose Turing Machine doesn’t halt for some positive cases but for others does not recursive?

Say language $$L$$ is recursively enumerable, but not recursive. Say $$a$$ and $$b$$ are symbols of the alphabet and $$w$$ a word. Say we have the following language:

$$L’ = \{ aw | w \in L \} \cup \{ bw | w \notin L \}$$

That is, $$L’$$ consists of the words that are in $$L$$ with an $$a$$ added at the beginning and the words that are not in $$L$$ with a $$b$$ at the beginning.

Is $$L’$$ not recursive? If we have the Turing Machine $$TM$$ that decides $$L’$$, $$TM$$ will halt for some positive cases ($$w \in L$$) but for other positive cases ($$w \notin L$$) it won’t halt. Is it therefore not recursive and recursively enumerable?

From what I understand:

• Recursively enumerable: the Turing Machine will always halt if $$w \in L$$, otherwise it may or not halt.

• Recursive: it always halts.

• Recursively enumerable, but not recursive: it only halts if $$w \in L$$; otherwise it loops.

• Not recursively enumerable: no Turing Machine exists.

So I don’t know how to classify a language whose Turing Machine halts for some of its words.

## Recursive function not exiting even after it satisfies the exit condition

You have been given an integer array A and a number K. Now, you need to find out whether any two different elements of the array A sum to the number K. Two elements are considered to be different if they lie at different positions in the array. If there exists such a pair of numbers, print “YES” (without quotes), else print “NO” without quotes.

Input : 5 9 5 4 3 2 1

Output: YES Since adding 5 and 4 will return 9 which is k, YES should be printed.

#include <iostream> #include <vector> using namespace std; void DoesPairExists(vector<int> ops,int result,bool& exitVal) {     if (ops.size() >= 2)     {         for (int i = ops.size()-2; i >= 0 ; i--)         {                //Always picking the last element and adding with the current              //element             int sum = ops[i] + ops.back();             if (sum == result)             {                 exitVal = true;                 break;             }         }         if (!exitVal)         {              //Even after adding the last element with all the elements, we              //didn't get the expected result, we don't need the last              //element.             ops.pop_back();             DoesPairExists(ops, result, exitVal);         }     } return; }  int main() {     bool bOutput = false;     int input, res;     vector<int> vec;     cin >> input >> res;     for (int i = 0; i < input; i++)     {         int x;         cin >> x;         vec.push_back(x);     }     DoesPairExists(vec, res, bOutput);     bOutput? cout << "YES" << endl : cout << "NO" << endl;     return 0; } 

Once the exitVal is set to true the control is not returning to the main function, instead it again calls DoesPairExists(). Can someone please help me out?